Rust 的 std::process::Command
允许通过 stdin
配置进程的标准输入方法,但该方法似乎只接受现有文件或管道。
给定一段字节,您将如何将其写入 Command
的标准输入?
最佳答案
您可以创建一个标准输入管道并在其上写入字节。
- 由于
Command::output
会立即关闭标准输入,您将不得不使用Command::spawn
。 Command::spawn
默认继承标准输入。您必须使用Command::stdin
来更改行为。
这是示例(playground):
use std::io::{self, Write};
use std::process::{Command, Stdio};
fn main() -> io::Result<()> {
let mut child = Command::new("cat")
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.spawn()?;
let child_stdin = child.stdin.as_mut().unwrap();
child_stdin.write_all(b"Hello, world!\n")?;
// Close stdin to finish and avoid indefinite blocking
drop(child_stdin);
let output = child.wait_with_output()?;
println!("output = {:?}", output);
Ok(())
}
关于rust - 在 Rust 中写入子进程的标准输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49218599/