Function 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)
5fn main() -> Result<()> {
6    let mut p = expectrl::spawn("sh")?;
7    p.get_process_mut().set_echo(true, None)?;
8
9    let mut shell = ReplSession::new(p, String::from("sh-5.1$"), Some(String::from("exit")), true);
10
11    shell.expect_prompt()?;
12
13    let output = exec(&mut shell, "echo Hello World")?;
14    println!("{:?}", output);
15
16    let output = exec(&mut shell, "echo '2 + 3' | bc")?;
17    println!("{:?}", output);
18
19    Ok(())
20}
More examples
Hide additional examples
examples/log.rs (line 4)
3fn main() -> Result<(), Error> {
4    let p = spawn("cat")?;
5    let mut p = expectrl::session::log(p, std::io::stdout())?;
6
7    #[cfg(not(feature = "async"))]
8    {
9        p.send_line("Hello World")?;
10        p.expect("Hello World")?;
11    }
12    #[cfg(feature = "async")]
13    {
14        futures_lite::future::block_on(async {
15            p.send_line("Hello World").await?;
16            p.expect("Hello World").await
17        })?;
18    }
19
20    Ok(())
21}
examples/ftp.rs (line 5)
4fn main() -> Result<(), Error> {
5    let mut p = spawn("ftp bks4-speedtest-1.tele2.net")?;
6    p.expect(Regex("Name \\(.*\\):"))?;
7    p.send_line("anonymous")?;
8    p.expect("Password")?;
9    p.send_line("test")?;
10    p.expect("ftp>")?;
11    p.send_line("cd upload")?;
12    p.expect("successfully changed.")?;
13    p.send_line("pwd")?;
14    p.expect(Regex("[0-9]+ \"/upload\""))?;
15    p.send(ControlCode::EndOfTransmission)?;
16    p.expect("Goodbye.")?;
17    Ok(())
18}
examples/interact.rs (line 15)
14fn main() {
15    let mut sh = spawn(SHELL).expect("Error while spawning sh");
16
17    println!("Now you're in interacting mode");
18    println!("To return control back to main type CTRL-] combination");
19
20    let mut stdin = Stdin::open().expect("Failed to create stdin");
21
22    sh.interact(&mut stdin, stdout())
23        .spawn(&mut InteractOptions::default())
24        .expect("Failed to start interact");
25
26    stdin.close().expect("Failed to close a stdin");
27
28    println!("Exiting");
29}
examples/check.rs (line 5)
4fn main() {
5    let mut session = spawn("python ./tests/source/ansi.py").expect("Can't spawn a session");
6
7    loop {
8        match check!(
9            &mut session,
10            _ = "Password: " => {
11                println!("Set password to SECURE_PASSWORD");
12                session.send_line("SECURE_PASSWORD").unwrap();
13            },
14            _ = "Continue [y/n]:" => {
15                println!("Stop processing");
16                session.send_line("n").unwrap();
17            },
18        ) {
19            Err(Error::Eof) => break,
20            result => result.unwrap(),
21        };
22    }
23}
examples/expect_line.rs (line 5)
4fn main() {
5    let mut session = expectrl::spawn("ls -al").expect("Can't spawn a session");
6
7    loop {
8        let m = session
9            .expect(Any::boxed(vec![
10                Box::new("\r"),
11                Box::new("\n"),
12                Box::new(Eof),
13            ]))
14            .expect("Expect failed");
15
16        println!("{:?}", String::from_utf8_lossy(m.as_bytes()));
17
18        let is_eof = m[0].is_empty();
19        if is_eof {
20            break;
21        }
22
23        if m[0] == [b'\n'] {
24            continue;
25        }
26
27        println!("{:?}", String::from_utf8_lossy(&m[0]));
28    }
29}