4 个版本
0.1.3 | 2023 年 7 月 25 日 |
---|---|
0.1.2 | 2021 年 8 月 23 日 |
0.1.1 | 2021 年 8 月 23 日 |
0.1.0 | 2021 年 8 月 22 日 |
#298 在 Unix API 中
每月 252 次下载
用于 2 crates
9KB
58 行
interactive_process
一个用于通过 stdio
与运行中的进程交互的微型 Rust 库。
在 Unix 中,一个常见的模式是程序通过标准输入输出 (stdio) 流产生或消费换行符分隔的文本。
此软件包提供了一个轻量级的包装器(非常轻量级,请参阅 src/lib.rs),在 Rust 内置的 std::process
上提供了一个整洁的小抽象。除了 std
,此软件包没有其他依赖项。
用法
请参阅 examples/ 目录中的示例。例如,这里是 echo_stream.rs
use interactive_process::InteractiveProcess;
use std::{process::Command, thread::sleep, time::Duration};
fn main() {
/// Use Rust's built-in `std::process` to construct a `Command`.
/// `examples/echo_stream.py` repeats back lines sent to it,
/// prefixed with "echo: ".
let cmd = Command::new("examples/echo_stream.py");
/// Pass this command to `InteractiveProcess`, along with a
/// callback. In this case, we'll print every line that the
/// process prints to `stdout`, prefixed by "Got: ".
let mut proc = InteractiveProcess::new(cmd, |line| {
println!("Got: {}", line.unwrap());
})
.unwrap();
/// Send some data, waiting in between.
/// The result of this is "Got: echo: data1" being printed by our callback,
/// since our callback preprends "Got: " and the child process prepends
/// "echo: ".
proc.send("data1").unwrap();
/// Sleep in this thread. Note that the process' `stdout` is processed in
/// another thread, so while this thread sleeps, that thread will pick
/// up the message printed by the child process and run the callback.
sleep(Duration::from_secs(1));
/// Repeat that a few more times, for kicks.
proc.send("data2").unwrap();
sleep(Duration::from_secs(1));
proc.send("data3").unwrap();
// If we don't sleep here, the process won't have time to reply
// before we kill it.
sleep(Duration::from_millis(1));
/// We're done with the process, but it is not self-terminating,
/// so we can't use `proc.wait()`. Instead, we'll take the `Child` from
/// the `InteractiveProcess` and kill it ourselves.
proc.close().kill().unwrap();
}
限制
我已在 Linux 上测试了此软件包的一些简单功能,但它还没有经过实战测试,并且我尚未在其他平台上进行测试。如果您遇到问题,请提交一个 issue,我会尽力与您一起解决这个问题。