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(())
}