如何通过 Rust 中的 stdin 向程序发送输入 [英] How to send input to a program through stdin in Rust
问题描述
我正在尝试用 Rust 编写一个 shell.shell 的功能之一是能够将输入重定向到文件,将文件重定向到输入,以及将程序的输出通过管道传输到另一个程序.我在 std
中使用 run::process_output
函数来运行程序并获取它们的输出,但我不知道如何将输入作为 stdin 发送到程序运行后.有没有办法创建一个直接连接到运行程序的对象,并像在标准输入中输入一样推送输入?
I am attempting to write a shell in Rust. One of the functions of a shell is being able to redirect input to a file, redirect a file to input, and pipe output of a program into another program. I am using the run::process_output
functions in std
to run programs and get their output, but I don't know how to send input as if it was stdin to a program after running it. Is there some way to create an object that is directly connected to the ran program and push in input like it was typed in stdin?
推荐答案
该程序演示了如何启动外部程序并将它们的 stdout -> stdin 一起传输:
This program demonstrates how you can launch external programs and stream their stdout -> stdin together:
use std::io::{BufRead, BufReader, BufWriter, Write};
use std::process::{Command, Stdio};
fn main() {
// Create some argument vectors for lanuching external programs
let a = vec!["view", "-h", "file.bam"];
let outsam = vec!["view", "-bh", "-o", "rust.bam", "-"];
let mut child = Command::new("samtools")
.args(&a)
.stdout(Stdio::piped())
.spawn()
.unwrap();
let outchild = Command::new("samtools")
.args(&outsam)
.stdin(Stdio::piped())
.spawn()
.unwrap();
// Create a handle and writer for the stdin of the second process
let mut outstdin = outchild.stdin.unwrap();
let mut writer = BufWriter::new(&mut outstdin);
// Loop over the output from the first process
if let Some(ref mut stdout) = child.stdout {
for line in BufReader::new(stdout).lines() {
let mut l: String = line.unwrap();
// Need to add an end of line character back to the string
let eol: &str = "\n";
l = l + eol;
// Print some select lines from the first child to stdin of second
if (l.chars().skip(0).next().unwrap()) == '@' {
// convert the string into bytes and write to second process
let bytestring = l.as_bytes();
writer.write_all(bytestring).unwrap();
}
}
}
}
这篇关于如何通过 Rust 中的 stdin 向程序发送输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!