Function expectrl::spawn

source ·
pub fn spawn<S: AsRef<str>>(cmd: S) -> Result<Session, Error>
Expand description

Spawn spawnes a new session.

It accepts a command and possibly arguments just as string. It doesn’t parses ENV variables. For complex constrictions use Session::spawn.

Example

use std::{thread, time::Duration, io::{Read, Write}};
use expectrl::{spawn, ControlCode};

let mut p = spawn("cat").unwrap();
p.send_line("Hello World").unwrap();

thread::sleep(Duration::from_millis(300)); // give 'cat' some time to set up
p.send(ControlCode::EndOfText).unwrap(); // abort: SIGINT

let mut buf = String::new();
p.read_to_string(&mut buf).unwrap();

assert_eq!(buf, "Hello World\r\n");
Examples found in repository?
examples/shell.rs (line 6)
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
fn main() -> Result<()> {
    let mut p = expectrl::spawn("sh")?;
    p.get_process_mut().set_echo(true, None)?;

    let mut shell = ReplSession::new(p, String::from("sh-5.1$"), Some(String::from("exit")), true);

    shell.expect_prompt()?;

    let output = exec(&mut shell, "echo Hello World")?;
    println!("{:?}", output);

    let output = exec(&mut shell, "echo '2 + 3' | bc")?;
    println!("{:?}", output);

    Ok(())
}
More examples
Hide additional examples
examples/log.rs (line 4)
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
fn main() -> Result<(), Error> {
    let p = spawn("cat")?;
    let mut p = expectrl::session::log(p, std::io::stdout())?;

    #[cfg(not(feature = "async"))]
    {
        p.send_line("Hello World")?;
        p.expect("Hello World")?;
    }
    #[cfg(feature = "async")]
    {
        futures_lite::future::block_on(async {
            p.send_line("Hello World").await?;
            p.expect("Hello World").await
        })?;
    }

    Ok(())
}
examples/ftp.rs (line 5)
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
fn main() -> Result<(), Error> {
    let mut p = spawn("ftp bks4-speedtest-1.tele2.net")?;
    p.expect(Regex("Name \\(.*\\):"))?;
    p.send_line("anonymous")?;
    p.expect("Password")?;
    p.send_line("test")?;
    p.expect("ftp>")?;
    p.send_line("cd upload")?;
    p.expect("successfully changed.")?;
    p.send_line("pwd")?;
    p.expect(Regex("[0-9]+ \"/upload\""))?;
    p.send(ControlCode::EndOfTransmission)?;
    p.expect("Goodbye.")?;
    Ok(())
}
examples/interact.rs (line 15)
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
fn main() {
    let mut sh = spawn(SHELL).expect("Error while spawning sh");

    println!("Now you're in interacting mode");
    println!("To return control back to main type CTRL-] combination");

    let mut stdin = Stdin::open().expect("Failed to create stdin");

    sh.interact(&mut stdin, stdout())
        .spawn(&mut InteractOptions::default())
        .expect("Failed to start interact");

    stdin.close().expect("Failed to close a stdin");

    println!("Exiting");
}
examples/check.rs (line 5)
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
fn main() {
    let mut session = spawn("python ./tests/source/ansi.py").expect("Can't spawn a session");

    loop {
        match check!(
            &mut session,
            _ = "Password: " => {
                println!("Set password to SECURE_PASSWORD");
                session.send_line("SECURE_PASSWORD").unwrap();
            },
            _ = "Continue [y/n]:" => {
                println!("Stop processing");
                session.send_line("n").unwrap();
            },
        ) {
            Err(Error::Eof) => break,
            result => result.unwrap(),
        };
    }
}
examples/expect_line.rs (line 5)
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
fn main() {
    let mut session = expectrl::spawn("ls -al").expect("Can't spawn a session");

    loop {
        let m = session
            .expect(Any::boxed(vec![
                Box::new("\r"),
                Box::new("\n"),
                Box::new(Eof),
            ]))
            .expect("Expect failed");

        println!("{:?}", String::from_utf8_lossy(m.as_bytes()));

        let is_eof = m[0].is_empty();
        if is_eof {
            break;
        }

        if m[0] == [b'\n'] {
            continue;
        }

        println!("{:?}", String::from_utf8_lossy(&m[0]));
    }
}