Created
January 22, 2024 08:20
-
-
Save Myestery/2950baaac42e1e6bf4f244cd0a4dce39 to your computer and use it in GitHub Desktop.
How to asynchronously run a command and pipe the output
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use tokio::process::Command; | |
use tokio::io::{self, AsyncBufReadExt}; | |
#[tokio::main] | |
async fn main() -> io::Result<()> { | |
let shell_command = "sleep 2 && echo \"how\" && sleep 10 && echo \"yes\""; | |
let mut child = Command::new("sh") | |
.arg("-c") | |
.arg(shell_command) | |
.stdout(std::process::Stdio::piped()) | |
.spawn() | |
.expect("Failed to spawn child process"); | |
let stdout = child.stdout.take().expect("Failed to open stdout"); | |
let reader = io::BufReader::new(stdout); | |
let mut lines = reader.lines(); | |
// Asynchronously read lines from the stdout | |
while let Some(line) = lines.next_line().await? { | |
println!("{}", line); | |
} | |
// Await the child process to finish | |
let status = child.await.expect("Child process encountered an error"); | |
println!("Process exited with status: {}", status); | |
Ok(()) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment