使用Rust处理管道数据stdin



我在Rust中使用stdin时遇到问题。我正在尝试从linux终端上的管道处理stdin-commg,例如grep。

echo "lorem ipsum" | grep <text>

我在铁锈中使用这个:

fn load_stdin() -> Result<String> {
let mut buffer = String::new();
let stdin = stdin();
stdin.read_line(&mut buffer)?;
return Ok(buffer);
}

但问题是,如果我没有引入任何提示写入的管道数据,我会返回Err。

所以基本上,如果我做一些类似的事情:

ls | cargo run
user@machine: ~ $ 

一切都很好。但如果我不管道任何stdin:

cargo run

程序将暂停并等待用户输入。

您可以使用atty机箱来测试您的标准输入是否被重定向:

use std::io;
use atty::Stream;
fn load_stdin() -> io::Result<String> {
if atty::is(Stream::Stdin) {
return Err(io::Error::new(io::ErrorKind::Other, "stdin not redirected"));
}
let mut buffer = String::new();
io::stdin().read_line(&mut buffer)?;
return Ok(buffer);
}
fn main() -> io::Result<()> {
println!("line: {}", load_stdin()?);
Ok(())
}

这会产生所需的行为:

$ echo "lorem ipsum" | cargo run
Finished dev [unoptimized + debuginfo] target(s) in 0.02s
Running `target/debug/playground`
line: lorem ipsum
$ cargo run
Finished dev [unoptimized + debuginfo] target(s) in 0.02s
Running `target/debug/playground`
Error: Custom { kind: Other, error: "stdin not redirected" }

最新更新