Capture Child Process Output With Command

Command::output runs an external program and hands back stdout, stderr, and exit status as bytes, while a missing binary returns Err instead of panicking.

RustCli Tooling

Code

rustsnippet
16 lines
use std::process::Command;

fn main() {
    // output() 把子进程的 stdout/stderr 收进内存,不透传到终端
    let output = Command::new("git")
        .arg("--version")
        .output()
        .expect("git should be available for this demo");

    println!("status: {}", output.status);
    println!("stdout: {}", String::from_utf8_lossy(&output.stdout));

    // 命令不存在:spawn 阶段就返回 Err,而不是 panic
    let missing = Command::new("definitely-not-a-real-binary").output();
    println!("missing command failed: {}", missing.is_err());
}

How it works

Count the function main as the entire surface area of Capture Child Process Output With Command.

Using it

Running the file prints labeled results such as status:, stdout:, missing command failed: — each operation’s effect is visible in the output.

Key statements

let missing = Command::new("definitely-not-a-real-binary").output();
.expect("git should be available for this demo");

Interactive Tools for This Topic

FAQ

What does Capture Child Process Output With Command print when run?
Execute the whole file; each printed line is prefixed with a label like `status:`, `stdout:`, `missing command failed:`.