如何使用 Rust 语言将 stdout 输出到终端执行 std::process::Command

Spi*_*man 5 rust


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);
}
Run Code Online (Sandbox Code Playgroud)
  1. 上面的代码运行良好,但仅在 docker 脚本完全运行后才打印输出,但我想在发生时查看 Linux 终端中的所有命令输出,并希望在发生时查看输出,
  2. 我尝试了文档中给出的所有组合并阅读了很多次,但不明白如何将标准输出重定向到终端窗口,

chu*_*500 7

根据文档, stdout 具有默认行为,具体取决于您启动子进程的方式:

与spawn或status一起使用时默认为继承,与输出一起使用时默认为管道。

因此,当您调用 时,标准输出会通过管道传输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
Run Code Online (Sandbox Code Playgroud)

现在我们了解了 stdout 当前的去向,如果您希望控制台获得流输出,请使用以下命令调用该进程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);
}
Run Code Online (Sandbox Code Playgroud)

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

bash -c "docker run ..."
Run Code Online (Sandbox Code Playgroud)

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