In Rust, how can I capture the output of a process with colors?

I would like to grab the output from another process (for example, git status), process it and print it with all the styles (bold, italic, underline) and colors. It is very important for me to continue the process so Stringthat I do not want to just print it.

In the Unix world, I think this will include escape codes, I'm not sure about the Windows world, but it matters to me too.

I know how to do this without colors:

fn exec_git() -> String {
    let output = Command::new("git")
        .arg("status")
        .output()
        .expect("failed to execute process");

    String::from_utf8_lossy(&output.stdout).into_owned()
}

Maybe I should use instead spawn?

+4
source share
2 answers

:

use std::process::Command;

fn main() {
    let output = Command::new("ls")
        .args(&["-l", "--color"])
        .env("LS_COLORS", "rs=0:di=38;5;27:mh=44;38;5;15")
        .output()
        .expect("Failed to execute");

    let sout = String::from_utf8(output.stdout).expect("Not UTF-8");
    let serr = String::from_utf8(output.stderr).expect("Not UTF-8");

    println!("{}", sout);
    println!("{}", serr);
}

:

total 68
-rw-r--r-- 4 root root 56158 Dec 23 00:00 [0m[44;38;5;15mCargo.lock[0m
-rw-rw-r-- 4 root root  2093 Dec  9 02:54 [44;38;5;15mCargo.toml[0m
drwxr-xr-x 1 root root  4096 Dec 30 15:24 [38;5;27msrc[0m
drwxr-xr-x 1 root root  4096 Dec 23 00:19 [38;5;27mtarget[0m

, ([44;, [0m ..). ANSI escape-, , .

, :

\u{1b}[0m\u{1b}[44;38;5;15mCargo.lock\u{1b}[0m

escape- ESC (\u{1b}), . , , .

Windows escape- ( , Windows 10?), , . , .

+1

git git -c color.status=always status

use std::process::Command;

fn main() {
    let output = Command::new("git")
        .arg("-c")
        .arg("color.status=always")
        .arg("status")
        .output()
        .expect("failed to execute process");

    let output = String::from_utf8_lossy(&output.stdout).into_owned();

    println!("{}", output);
}

git status. , , , , (, COLORTERM).

+2

Source: https://habr.com/ru/post/1665310/


All Articles