17 个不稳定版本 (3 个重大更新)
0.4.1 | 2022年6月27日 |
---|---|
0.4.0 | 2022年6月26日 |
0.3.3 | 2022年6月26日 |
0.2.6 | 2022年6月25日 |
0.1.3 | 2022年5月21日 |
#1050 in 异步
每月167次 下载
在 3 crates 中使用
20KB
398 行
process-stream
将 tokio::process::Command
包装为 future::stream
.
此库提供 ProcessExt 以创建自己的自定义进程
安装
process-stream = "0.3.1"
示例用法
从 Vec<String>
或 Vec<&str>
use process_stream::{Process, ProcessExt, StreamExt};
use std::io;
#[tokio::main]
async fn main() -> io::Result<()> {
let ls_home: Process = vec!["/bin/ls", "."].into();
let mut stream = ls_home.spawn_and_stream()?;
while let Some(output) = stream.next().await {
println!("{output}")
}
Ok(())
}
从 Path/PathBuf/str
use process_stream::{Process, ProcessExt, StreamExt};
use std::io;
#[tokio::main]
async fn main() -> io::Result<()> {
let mut process: Process = "/bin/ls".into();
// block until process completes
let outputs = process.spawn_and_stream()?.collect::<Vec<_>>().await;
println!("{outputs:#?}");
Ok(())
}
新建
use process_stream::{Process, ProcessExt, StreamExt};
use std::io;
#[tokio::main]
async fn main() -> io::Result<()> {
let mut ls_home = Process::new("/bin/ls");
ls_home.arg("~/");
let mut stream = ls_home.spawn_and_stream()?;
while let Some(output) = stream.next().await {
println!("{output}")
}
Ok(())
}
终止
use process_stream::{Process, ProcessExt, StreamExt};
use std::io;
#[tokio::main]
async fn main() -> io::Result<()> {
let mut long_process = Process::new("/bin/app");
let mut stream = long_process.spawn_and_stream()?;
tokio::spawn(async move {
while let Some(output) = stream.next().await {
println!("{output}")
}
})
// process some outputs
tokio::time::sleep(std::time::Duration::new(10, 0)).await;
// close the process
long_process.kill().await;
Ok(())
}
与运行进程通信
use process_stream::{Process, ProcessExt, StreamExt};
#[tokio::main]
async fn main() -> io::Result<()> {
let mut process: Process = Process::new("sort");
// Set stdin (by default is set to null)
process.stdin(Stdio::piped());
// Get Stream;
let mut stream = process.spawn_and_stream().unwrap();
// Get writer from stdin;
let mut writer = process.take_stdin().unwrap();
// Spawn new async task and move stream to it
let reader_thread = tokio::spawn(async move {
while let Some(output) = stream.next().await {
if output.is_exit() {
println!("DONE")
} else {
println!("{output}")
}
}
});
// Spawn new async task and move writer to it
let writer_thread = tokio::spawn(async move {
writer.write(b"b\nc\na\n").await.unwrap();
writer.write(b"f\ne\nd\n").await.unwrap();
});
// Wait till all threads finish
writer_thread.await.unwrap();
reader_thread.await.unwrap();
// Result
// a
// b
// c
// d
// e
// f
// DONE
Ok(())
}
依赖项
~4–15MB
~147K SLoC