【问题标题】:How do I stdout into terminal executing std::process::Command in Rust language如何在 Rust 语言中标准输出到终端执行 std::process::Command
【发布时间】:2020-05-14 20:14:18
【问题描述】:

fn main() {
    let output = Command::new("/bin/bash")
                .args(&["-c", "docker","build", "-t", "postgres:latest", "-", "<>", "dockers/PostgreSql"])
                .output()
                .expect("failed to execute process");

    println!("{:?}", output);
}
  1. 以上代码运行良好,但仅在 docker 脚本完全运行后才打印输出,但我想在我的 Linux 终端中看到所有命令输出,并希望看到输出,
  2. 我尝试了文档中给出的所有组合并阅读了很多遍,不明白,如何将stdout重定向到我的终端窗口,

【问题讨论】:

标签: rust


【解决方案1】:

根据the documentation,标准输出的默认行为取决于您启动子进程的方式:

与 spawn 或 status 一起使用时默认为继承,与 output 一起使用时默认为 piped。

因此,当您调用 output() 时,标准输出将通过管道传输。管道是什么意思?这意味着子进程的输出将被定向到父进程(在这种情况下是我们的 rust 程序)。 std::process::Command 好心给我们这个字符串:

use std::process::{Command, Stdio};

let output = Command::new("echo")
    .arg("Hello, world!")
    .stdout(Stdio::piped())
    .output()
    .expect("Failed to execute command");

assert_eq!(String::from_utf8_lossy(&output.stdout), "Hello, world!\n");
// Nothing echoed to console

现在我们了解了标准输出当前的去向,如果您希望控制台获得流式输出,请使用spawn() 调用该进程:

use std::process::Command;

fn main() {

    let output = Command::new("/bin/bash")
                .args(&["-c", "echo hello world"])
                .spawn()
                .expect("failed to execute process");


    println!("{:?}", output);
}

请注意,在后面的示例中,我将完整的echo hello world 命令传递到一个字符串中。这是因为bash -c 将其 arg 按空格分割并运行它。如果您在控制台中通过 bash shell 执行 docker 命令,您会说:

bash -c "docker run ..."

上面的引号告诉终端将第三个参数保持在一起,而不是用空格分隔它。我们的 rust 数组中的等价物是在单个字符串中传递完整的命令(当然,假设您希望通过 bash -c 调用它)。

【讨论】:

  • 这个设置对我有用fn run_command() { let _output = Command::new("/bin/bash") .arg("-c") .arg("docker build -t postgres:latest - &lt; dockers/PostgreSql") .spawn() .expect("failed to execute process"); }
  • 实际上在调试过程中,我在 cargo 中更改了包名称,但忘记在可执行文件中运行新名称,所以我整晚都看到没有任何变化,我正在更改和构建并且没有任何变化,所以认为文档很糟糕,文档就足够了,我的错我很挣扎,
【解决方案2】:

我对另一个答案很幸运,但我不得不对其进行一些修改。对我来说,我 需要添加wait方法:

use std::{io, process::Command};

fn main() -> io::Result<()> {
   let mut o = Command::new("rustc").arg("-V").spawn()?;
   o.wait()?;
   Ok(())
}

否则父程序将在子程序之前结束。

https://doc.rust-lang.org/std/process/struct.Child.html#method.wait

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-06-28
    • 1970-01-01
    • 2015-02-24
    • 1970-01-01
    • 2016-06-05
    • 2011-11-14
    • 1970-01-01
    相关资源
    最近更新 更多