o4-mini-2025-04-16· OpenAI LMArena Human Preference 140K
rust: execute command with stdout & stderr piped, but also store them in a variabel
- User
rust: execute command with stdout & stderr piped, but also store them in a variabel
- Assistant
Here are two approaches in “plain” Rust.
- If you just want to run a command, wait for it to finish, and then grab its stdout/stderr as
String(no real‐time printing), useCommand::output(). - If you’d like to stream stdout/stderr to your own terminal as the subprocess runs, and also accumulate them in two Rust
Strings, you can spawn the child, take its pipes, and in two threads read, tee tostdout/stderr, and buffer.
1) Simple capture (no live‐printing)
use std::process::Command; use std::str; fn main() -> anyhow::Result<()> { let output = Command::new("ls") .arg("-lha") .output()?; // <-- runs and waits let stdout = String::from_utf8_lossy(&output.stdout); let stderr = String::from_utf8_lossy(&output.stderr); println!("EXIT CODE: {}", output.status); println!("STDOUT:\n{}", stdout); eprintln!("STDERR:\n{}", stderr); Ok(()) }– Pros: super‐simple.
– Cons: you see nothing until the child exits.
2) Live‐stream + buffer
use std::io::{self, Read, Write}; use std::process::{Command, Stdio}; use std::thread; fn run_and_capture(cmd: &str, args: &[&str]) -> io::Result<(String, String)> { // 1) spawn child with piped stdout/stderr let mut child = Command::new(cmd) .args(args) .stdout(Stdio::piped()) .stderr(Stdio::piped()) .spawn()?; // 2) take the pipes let mut out_pipe = child.stdout.take().unwrap(); let mut err_pipe = child.stderr.take().unwrap(); // 3) thread to read stdout, tee to real stdout, accumulate bytes let stdout_handle = thread::spawn(move || { let mut buf = [0; 1024]; let mut acc = Vec::new(); loop { match out_pipe.read(&mut buf) { Ok(0) => break, // EOF Ok(n) => { // write to your terminal io::stdout().write_all(&buf[..n]).ok(); io::stdout().flush().ok(); // accumulate acc.extend_from_slice(&buf[..n]); } Err(e) => { eprintln!("error reading stdout: {}", e); break; } } } acc }); // 4) same for stderr let stderr_handle = thread::spawn(move || { let mut buf = [0; 1024]; let mut acc = Vec::new(); loop { match err_pipe.read(&mut buf) { Ok(0) => break, Ok(n) => { io::stderr().write_all(&buf[..n]).ok(); io::stderr().flush().ok(); acc.extend_from_slice(&buf[..n]); } Err(e) => { eprintln!("error reading stderr: {}", e); break; } } } acc }); // 5) wait for child to exit let status = child.wait()?; println!("Child exited with: {}", status); // 6) join threads and convert let stdout_bytes = stdout_handle.join().unwrap(); let stderr_bytes = stderr_handle.join().unwrap(); let stdout_str = String::from_utf8_lossy(&stdout_bytes).into_owned(); let stderr_str = String::from_utf8_lossy(&stderr_bytes).into_owned(); Ok((stdout_str, stderr_str)) } fn main() -> io::Result<()> { let (out, err) = run_and_capture("ping", &["-c", "3", "rust-lang.org"])?; println!("\n=== Buffered STDOUT ===\n{}", out); println!("=== Buffered STDERR ===\n{}", err); Ok(()) }Explanation:
- We spawn the child with
stdout/stderrpiped. - We
take()each pipe, spawn a thread that:- Reads chunks (e.g. 1024 bytes).
- Writes them immediately to our parent’s terminal.
- Appends them into a
Vec<u8>buffer.
- After the child exits, we join the threads, convert buffers into
Strings, and return them.
This gives you live output and captured buffers you can inspect later.
—Hope this helps! Let me know if you need a async/Tokio version or anything else.
- If you just want to run a command, wait for it to finish, and then grab its stdout/stderr as
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.