Created
November 29, 2023 18:34
-
-
Save SCP002/983abc8328ec739909b3be9f4a3cd2fa to your computer and use it in GitHub Desktop.
Rust: Start process. Keep StdOut and StdErr in the original order. Display output real time character by character. Capture output on exit.
This file contains hidden or 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
// Add to your Cargo.toml: | |
// [dependencies] | |
// utf8-chars = "1.0.0" | |
// subprocess = { version = "0.2.10", git = "https://github.com/SCP002/rust-subprocess.git" } | |
use std::io; | |
use std::io::BufReader; | |
use std::io::Write; | |
use subprocess::Exec; | |
use subprocess::ExitStatus; | |
use subprocess::Redirection; | |
use utf8_chars::BufReadCharsExt; | |
fn main() { | |
let mut proc = Exec::cmd("my-executable-name") | |
.arg("arg1") | |
.stdout(Redirection::Pipe) | |
.stderr(Redirection::Merge) | |
.popen() | |
.unwrap(); | |
let mut out = String::new(); | |
BufReader::new(proc.stdout.as_ref().unwrap()) | |
.chars() | |
.filter_map(|c| c.ok()) | |
.for_each(|c| { | |
print!("{}", c); | |
io::stdout().flush().unwrap(); | |
out.push(c); | |
}); | |
let exit_status = proc.wait().unwrap(); | |
println!("{}", "-".repeat(30)); | |
println!("{}", out); | |
let exit_code = match exit_status { | |
ExitStatus::Exited(c) => c as i32, | |
_ => -1, | |
}; | |
println!("Exit code: {:?}", exit_code); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment