I have this small program in rust, not in a cargo project.
use std::process::Command;
fn main() {
let result= Command::new("git").arg("status").output().expect("Ok");
println!("{:?}", result);
}
but after building and running it I get
Output { status: ExitStatus(unix_wait_status(0)), stdout: "On branch main\nYour branch is up to date with 'origin/main'.\n\nUntracked files:\n (use \"git add <file>...\" to include in what will be committed)\n\tbasics/guessing_game/\n\tcmdtest\n\tcmdtest.rs\n\nnothing added to commit but untracked files present (use \"git add\" to track)\n", stderr: "" }
If I try:
use std::process::Command;
fn main() {
let result= Command::new("git").arg("status").output().expect("Ok");
println!("{:?}", result.stdout);
}
I get
[79, 110, 32, 98, 114, 97, 110, 99, 104, 32, 109, 97, 105, 110, 10, 89, 111, 117, 114, 32, 98, 114, 97, 110, 99, 104, 32, 105, 115, 32, 117, 112, 32, 116, 111, 32, 100, 97, 116, 101, 32, 119, 105, 116, 104, 32, 39, 111, 114, 105, 103, 105, 110, 47, 109, 97, 105, 110, 39, 46, 10, 10, 85, 110, 116, 114, 97, 99, 107, 101, 100, 32, 102, 105, 108, 101, 115, 58, 10, 32, 32, 40, 117, 115, 101, 32, 34, 103, 105, 116, 32, 97, 100, 100, 32, 60, 102, 105, 108, 101, 62, 46, 46, 46, 34, 32, 116, 111, 32, 105, 110, 99, 108, 117, 100, 101, 32, 105, 110, 32, 119...
How can I print the string inside stdout and not numbers, in a user friendly format?
>Solution :
stdout may not be valid unicode, in which case you cannot print it. If you’re sure it will be (which is probably the case with git), you can use String::from_utf8().unwrap():
fn main() {
let result = Command::new("git").arg("status").output().expect("Ok");
println!("{}", String::from_utf8(result.stdout).unwrap());
}
If you don’t know, you can either check the Result from_utf8() returns, or use String::from_utf8_lossy() to turn invalid characters into U+FFFD REPLACEMENT CHARACTER �:
fn main() {
let result = Command::new("git").arg("status").output().expect("Ok");
println!("{}", String::from_utf8_lossy(&result.stdout));
}