gpt4 book ai didi

rust - 如何捕获通过管道传输到 Rust 程序的进程的输出?

转载 作者:行者123 更新时间:2023-11-29 07:52:15 27 4
gpt4 key购买 nike

我知道如何读取命令行参数,但我在从管道读取命令输出时遇到困难。

  1. 使用管道将输出数据的程序 (A) 连接到我的 Rust 程序:

    A | R
  2. 程序应逐行处理数据。

    $密码| cargo run 应该打印 pwd 输出。

    $ 查找。 | cargo run 应该输出超过 1 行的 find 命令输出。

最佳答案

使用BufRead::lineslocked handle to standard input 上:

use std::io::{self, BufRead};

fn main() {
let stdin = io::stdin();
for line in stdin.lock().lines() {
let line = line.expect("Could not read line from standard in");
println!("{}", line);
}
}

如果你想重用String的分配,你可以使用循环形式:

use std::io::{self, Read};

fn main() {
let stdin = io::stdin();
let mut stdin = stdin.lock(); // locking is optional

let mut line = String::new();

// Could also `match` on the `Result` if you wanted to handle `Err`
while let Ok(n_bytes) = stdin.read_to_string(&mut line) {
if n_bytes == 0 { break }
println!("{}", line);
line.clear();
}
}

关于rust - 如何捕获通过管道传输到 Rust 程序的进程的输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49733027/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com