我正在尝试在Rust中编写一个shell。 shell的一个功能是能够将输入重定向到文件,重定向文件以输入,并将程序的输出传送到另一个程序。我使用std
中的run::process_output
函数来运行程序并获取它们的输出,但是我不知道如何在运行后像输入stdin一样发送输入。有什么方法可以创建一个直接连接到跑步程序的对象,并像输入stdin一样输入输入内容?如何通过标准输入发送到一个程序在Rust中
4
A
回答
1
您需要一个正在运行的进程的句柄才能完成此操作。
// spawn process
let mut p = std::process::Command::new(prog).arg(arg).spawn().unwrap();
// give that process some input, processes love input
p.stdin().get_mut_ref().write_str(contents);
// wait for it to complete, you may need to explicitly close stdin above
// i.e. p.stdin().get_mut_ref().close();
p.wait();
上面应该让你发送任意输入到一个进程。如果生成的进程读取到eof,就像许多程序一样,关闭stdin管道非常重要。
3
此程序演示了如何启动外部程序和流的标准输出 - >标准输入在一起:
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();
}
}
}
}
0
迈克尔的回答的更新版本。如果你的输出/输入小,你可以将它读入以下方式的字符串和管道回:
let output = Command::new("ls").arg("-aFl")
.output().unwrap().stdout;
let output = String::from_utf8_lossy(&output);
println!("First program output: {:?}", output);
let put_command = Command::new("my_other_program")
.stdin(Stdio::piped())
.spawn().unwrap();
write!(put_command.stdin.unwrap(), "{}", output).unwrap();
相关问题
- 1. 如何通过HTTP发送一个进程的标准输出
- 2. 通过标准输入发送SIGINT
- 3. 发送SIGINT到过程通过发送CTRL-C至标准输入
- 4. 如何通过标准输入Python中
- 5. 发送一个Json数组在输入标准输入
- 6. 发送标准输入到Arduino C#
- 7. 发送.mov文件通过管道的ffmpeg(标准输入)
- 8. 如何写入另一个应用程序的标准输入?
- 9. 正在发送到标准输出的过程数据
- 10. 如何通过程序发送返回(输入按钮)字符
- 11. 顺序发送标准输出从subprocess.Popen通过套接字
- 12. 标准输入/输出在C#过程
- 13. 通过onclick发送输入
- 14. 可以发送标准通知的过滤器应用程序
- 15. C#程序标准输入
- 16. 进程通信中的管道标准输入/标准输出。
- 17. 如何更改另一程序的标准输入/输出?
- 18. 把管道输入到标准输入另一个进程
- 19. 巴什 - 如何将参数传递到通过标准输入
- 20. 在多线程应用程序中通过标准I/O输入
- 21. 如何处理标准输入到标准输出在PHP?
- 22. Python Popen发送到标准输入上处理,接收标准输出
- 23. 发送文本到Windows控制台应用程序的标准输入
- 24. 通过标准输入与标准输出stdout和stdr在Python中的交互
- 25. 如何通过使用另一个线程来停止正在从标准输入流中扫描的线程?
- 26. Pydev:发送标准输出到一个真正的(tty)终端
- 27. 发送一个文件到标准输出C
- 28. 如何将参数作为输入发送到mysql程序中?
- 29. 如何通过python发送输入到C++
- 30. 查询标准通过表格输入
可能'的std ::运行:: Process',你可以得到'Reader'和'作家'为'stdout'和'stdin' – Arjan