← 中文资源

简体中文版本

用 Command 捕获子进程输出

Command::output 把外部程序的 stdout、stderr 和退出状态以字节形式收回,配合 from_utf8_lossy 转成文本;命令不存在时 spawn 返回 Err,可以用 is_err 优雅探测。

阅读英文原文

实现说明

用 Command 捕获子进程输出的核心是函数 main。

使用要点

  • 演示输出是带标签的(status:、stdout:、missing command failed:),每个操作都会留下自己的一行标注。

常见问题

运行「用 Command 捕获子进程输出」会打印什么?

运行文件本身,status:、stdout:、missing command failed: 这些前缀各对应一段演示逻辑。

核心语句

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

代码示例

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());
}