简体   繁体   中英

How to pass real-time stdout line of a shell command to function in rust?

I want to get the real time output of a command line-by-line and pass the line to another function for further processing. I have the following code for reading the output:

fn output(x: &str) -> Result<(), Error> {
    let stdout = Command::new("strace")
        .args(&["-p", x])
        .stdout(Stdio::piped())
        .spawn()?
        .stdout
        .ok_or_else(|| Error::new(ErrorKind::Other,"Could not capture standard output."))?;

    let reader = BufReader::new(stdout);
    
    reader
        .lines()
        .filter_map(|line| line.ok())
        .for_each(|line| println!("hello {}", line));

     Ok(())
}

I tried changing the.for_each to pass it into the function, but it didn't work. It still printed out the normal output and after adding a println;(), for debugging. I've found that the lines don't even get to the function. I'm stuck. Please help!

Following @justinas's comment I replaced the "stdout" with "stderr" in my code and it worked!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM