【问题标题】:Running an external process in Rust在 Rust 中运行外部进程
【发布时间】:2014-10-21 02:31:03
【问题描述】:

我看到了这个问题In Rust, how do I invoke a system command and capture its output?,但似乎有些事情发生了变化。那么我现在如何在 Rust 中运行外部进程呢?

【问题讨论】:

标签: rust


【解决方案1】:

你试过std::io::process::Command吗?

你可以试试类似的。

let process = match std::io::process::Command::new("ls")
                       .args(&["-l", "/home/hduser"])
                       .spawn() {
        Ok(process) => process,
        Err(err)    => panic!("Running process error: {}", err),
};

let output = match process.wait_with_output() {
        Ok(output)  => output,
        Err(err)    => panic!("Retrieving output error: {}", err),
};

let stdout = match std::string::String::from_utf8(output.output) {
        Ok(stdout)  => stdout,
        Err(err)    => panic!("Translating output error: {}", err),
};

print!("{}", stdout);

您不必生成进程,但这是 Rust 最擅长的,为什么不呢。 Command::new 返回一个Optionwait_with_output() 返回一个IoResult,而from_utf8 返回一个Result,所以我使用了匹配表达式来解包结果,但您也可以轻松地使用.ok().expect("Some descriptive text for error")匹配表达式。

没有生成和匹配表达式的示例:

let process = std::io::process::Command::new("pwd")
                              .output()
                              .ok()
                              .expect("Failed to execute");
let out = std::string::String::from_utf8(process.output)
                              .ok()
                              .expect("Failed to read"));
println!("{}", out);

【讨论】:

  • .ok().expect("...") 在当今的 Rust 中被认为是一种反模式 - 可以直接在 Result 上使用 expect("...")。好处是Result::expect 会生成一条错误消息,其中包含错误原因(很像带有显式match 的代码示例),Option::expect 无法做到这一点,因为结果的错误部分在ResultOption 的转换。
  • 在现代 rust 中这是std::process::Command
猜你喜欢
  • 2022-11-26
  • 1970-01-01
  • 2020-02-24
  • 2012-08-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-11
相关资源
最近更新 更多