使用Command struct,我如何向标准输出和标准错误缓冲区添加前缀?
我希望输出看起来像这样:
[stdout] things are good.
[sterr] fatal: repository does not exist.这也可以很好地应用于程序的main stdout,这样程序打印的任何东西都会有这样的前缀。
这是我目前拥有的代码:
let output = Command::new("git").arg("clone").output().unwrap_or_else(|e| {
panic!("Failed to run git clone: {}", e)
});发布于 2015-04-06 04:34:01
我不相信你现在能做你真正想做的事。理想情况下,您可以为Process::stdout方法提供Write的实现者。不幸的是,set of choices for Stdio是稀疏的。也许您可以将其作为Rust 1.1的一个特性请求,或者创建一个crate来开始充实一些细节(比如跨平台兼容性)。
如果删除stdout / stderr的交错是可以接受的,那么这个解决方案可能会有所帮助:
use std::io::{BufRead,BufReader};
use std::process::{Command,Stdio};
fn main() {
let mut child =
Command::new("/tmp/output")
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn().unwrap();
if let Some(ref mut stdout) = child.stdout {
for line in BufReader::new(stdout).lines() {
let line = line.unwrap();
println!("[stdout] {}", line);
}
}
if let Some(ref mut stderr) = child.stderr {
for line in BufReader::new(stderr).lines() {
let line = line.unwrap();
println!("[stderr] {}", line);
}
}
let status = child.wait().unwrap();
println!("Finished with status {:?}", status);
}https://stackoverflow.com/questions/29458970
复制相似问题