How to intercept stdout and stderr when execute shell command

How to intercept stdout and stderr when execute shell command,cuz i want to check if the output contains the string specified like ERROR,FAILED.and stdout and stderr cannot be displayed until all shells have been executed,anyone can told me how to do?

and my source does not works

use std::process::Stdio;

use tokio::io::{AsyncBufReadExt, AsyncReadExt, BufReader};
use tokio::process::Command;
use tokio_stream::StreamExt;

pub async fn do_shell_new(command: &str) -> anyhow::Result<()> {
    let mut cmd = Command::new("sh")
        .arg("-c")
        .arg(command)
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()?;

    tokio::spawn(async move {

        let mut buffer = String::new();
        let stdout = cmd.stdout.take().unwrap();
        let mut reader = BufReader::new(stdout);
        while let Ok(size) = reader.read_line(&mut buffer).await {
            println!("into while size: {}",size);
            if size == 0 {
                break;
            }
            let line = buffer.trim_end().to_string();
            buffer.clear();

            if line.contains("ERROR") || line.contains("FAILED") || line.contains("[ERROR]") {
                eprintln!("Error output (stdout): {}", line);
            } else {
                println!("{}", line);
            }
        }
    });
    
   match cmd.wait().await {
       Ok(exit_status) => {
           println!("Command exited with status: {:?}", exit_status)
       }
       Err(e) => {
           println!("Command failed with error: {:?}", e);
       }
   };

    Ok(())
}

thx, i try it but did not works

If you give us some info, some code of what you tried you will find that someone here will have a better answer on how to help. Also be sure to show what errors you got and/or better describe what not works.

If you move this line to before the tokio::spawn call your code will compile, but I haven't tried running it:

    let stdout = cmd.stdout.take().unwrap();

Playground

There's a library with convenience methods for such tasks:

2 Likes

it's cool! i will try it thx

it seems works on linux,but something wrong when macos

If you'd like more help, we’ll need to know what code you ran, and what specific errors or problems you encountered.

hey man thank u very much!~ it works now!~

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.