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.
Code
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
Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.
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:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.