frencis1
frencis1

Reputation: 35

Rust: Write stdout into a buffer or String

I'm trying to spawn a process and log its stdout to a file.

My attempt was:

let mut log = String::new();

let output = Command::new("git")
        .current_dir(&cwd)
        .arg("pull")
        .arg("--rebase=merges")
        .output()
        .expect("Error doing git pull");

log.push_str("\nOUTPUT\n");
log.push_str(&output.stdout);

But this gives an error of mismatched types. How can I capture output.stdout to write into a String, or better, to a file?

Thank you!

Upvotes: 3

Views: 6633

Answers (1)

loops
loops

Reputation: 5635

Command output is represented as a series of bytes. Use std::str::from_utf8 to convert it to a str:

use std::str;
log.push_str(match str::from_utf8(&output.stdout) {
    Ok(val) => val,
    Err(_) => panic!("got non UTF-8 data from git"),
});

Try it in the playground

Upvotes: 5

Related Questions