首页 > 解决方案 > 如何在作为子进程运行的 shell 中执行命令?

问题描述

如何在 Rust 中调用系统命令并捕获其输出的答案?,我可以执行一个命令,该命令本身会产生一个 shell 来执行命令。

use std::process::Command;

Command::new("sh")
    .spawn()
    .expect("sh command failed to start");

是否可以在这个新获得的 shell 中执行来自 Rust 的命令?

标签: rust

解决方案


let mut child = Command::new("sh").stdin(Stdio::piped())
    .stderr(Stdio::piped())
    .stdout(Stdio::piped())
    .spawn()?;

child.stdin
    .as_mut()
    .ok_or("Child process stdin has not been captured!")?
    .write_all(b"something...")?;

let output = child.wait_with_output()?;

来源:Rust Cookbook中的外部命令


推荐阅读