std::process::Command for spawning external processes
Marcus Chen
Jan 2026
1 tab
use std::process::Command;
fn main() -> std::io::Result<()> {
let output = Command::new("ls")
.arg("-la")
.output()?;
if output.status.success() {
let stdout = String::from_utf8_lossy(&output.stdout);
println!("{}", stdout);
} else {
eprintln!("Command failed");
}
Ok(())
}
1 file · rust
Explain with highlit
std::process::Command runs external programs and captures their output. I use it for CLI tools that wrap other commands, build scripts, or integration tests. Methods like .arg(), .env(), and .current_dir() configure the process. .output() runs and waits, returning stdout/stderr. .spawn() starts the process without waiting. For streaming output, use .stdout(Stdio::piped()) and read from the child's handles. Always check the exit status. I use Command for running formatters, compilers, or shell scripts from Rust. It's safer than shell-ing out because you control arguments explicitly, avoiding injection vulnerabilities.