How do I invoke a system command in Rust and capture its output?

前端 未结 3 2067
有刺的猬
有刺的猬 2020-11-30 00:49

Is there a way to invoke a system command, like ls or fuser in Rust? How about capturing its output?

3条回答
  •  我在风中等你
    2020-11-30 01:27

    std::process::Command allows for that.

    There are multiple ways to spawn a child process and execute an arbitrary command on the machine:

    • spawn — runs the program and returns a value with details
    • output — runs the program and returns the output
    • status — runs the program and returns the exit code

    One simple example from the docs:

    use std::process::Command;
    
    Command::new("ls")
            .arg("-l")
            .arg("-a")
            .spawn()
            .expect("ls command failed to start");
    

提交回复
热议问题