gpt4 book ai didi

rust - 我如何将 stdout 输出到以 Rust 语言执行 std::process::Command 的终端

转载 作者:行者123 更新时间:2023-12-03 11:43:11 24 4
gpt4 key购买 nike


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 重定向到我的终端窗口,

最佳答案

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

Defaults to inherit when used with spawn or status, and defaults to piped when used with output.

因此当您调用 output() 时,stdout 将通过管道传输。管道是什么意思?这意味着子进程的输出将被定向到父进程(在这种情况下是我们的 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

现在我们了解了 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);
}

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

bash -c "docker run ..."

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

关于rust - 我如何将 stdout 输出到以 Rust 语言执行 std::process::Command 的终端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61806612/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com