I'm trying to capture stdout from accoreconsole, a cli version of AutoCAD. I don't understand why but for some reason the last output from accoreconsole (which doesn't seem to have any newline character) does not get captured until there are a newline. Even when the application exits with what seems to be without a newline it does not get captured by my BufReader. But when I run it in a regular terminal it works just fine and I see all output (the last Command: line). Same thing when accoreconsole prompts the user for input.
Here's what I've tried:
use std::io::stdout;
use std::io::Write;
use std::str;
use tokio::io::{AsyncReadExt, BufReader};
use tokio::process::Command;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut child = Command::new("c:\\Program Files\\Autodesk\\Autocad 2024\\accoreconsole.exe")
.args(&["/i", r"c:\dev\1.dwg", "/s", r"c:\dev\test.scr"])
.stdout(std::process::Stdio::piped())
.spawn()
.unwrap();
let proc_stdout = child.stdout.take().expect("Failed to open stdout");
let mut reader = BufReader::new(proc_stdout);
let mut buffer = [0; 1];
loop {
let bytes_read = reader.read(&mut buffer).await.unwrap();
if bytes_read > 0 {
let string_buf = str::from_utf8(&buffer[..bytes_read]).unwrap();
print!("{}", string_buf);
let _ = stdout().flush();
} else {
// there should be logic to handle EOF somewhere here...
}
}
Ok(())
}
I'm not even able to recreate the issue using unflushed stdout:
use std::io::stdout;
use std::io::Write;
fn main() {
let mut counter = 0;
let output = "Hello world!".to_string();
loop {
let mut char_iter = output.chars();
while let Some(c) = char_iter.next() {
print!("{}", c);
let _ = stdout().flush();
std::thread::sleep(std::time::Duration::from_millis(50));
}
println!("_");
if counter == 3 {
print!("#### gets flushed on application exit");
std::thread::sleep(std::time::Duration::from_millis(1000));
break;
}
counter += 1;
}
}
The "#### gets flushed on application exit"-part is flushed and captured when the application exits.
Are there different ways to output to stdout? Or why doesn't my Rust application capture the prompts or last output of the accoreconsole process?
Thanks!