在Rust中,我如何将彩色文本打印到终端?

46
如何使用Rust将彩色文本输出到终端?我尝试使用在this python answer中找到的特殊转义字符,但它们只是字面打印出来。这是我的代码:
fn main() {
    println!("\033[93mError\033[0m");
}

1
这似乎是 https://dev59.com/q1wY5IYBdhLWcg3wATpt 的重复。 - Garret Wilson
好观点!我在发布前的搜索中确实没有找到那个问题。这是否意味着我们应该关闭这个问题? - Sylvester Kruin
1
是的,在完美的世界中,后面的问题可能应该被关闭,并附上一个链接,说明它是重复的原始问题。但我对Rust还很新,没有仔细阅读这些帖子,所以我将其保留为原样,并注明了重复。 - Garret Wilson
3个回答

73
你可以使用colored crate来实现这个功能。下面是一个简单的例子,包含多种颜色和格式:
use colored::Colorize;

fn main() {
    println!(
        "{}, {}, {}, {}, {}, {}, and some normal text.",
        "Bold".bold(),
        "Red".red(),
        "Yellow".yellow(),
        "Green Strikethrough".green().strikethrough(),
        "Blue Underline".blue().underline(),
        "Purple Italics".purple().italic()
    );
}

示例颜色输出:

colored and formatted text in the terminal with Rust

每个格式函数(red()italics()等)都可以单独使用,也可以与其他函数组合使用。但是,如果你将颜色与其他颜色组合使用,只有最后设置的颜色会显示出来。

3
另一个需要检查的箱子是 https://lib.rs/crates/termcolor,以及它的包装器 https://lib.rs/crates/termcolor_output(免责声明 - 我创建了后者,但没有前者)。 - Cerberus
1
@Cerberus,如果你愿意的话,我鼓励你再发一篇答案!越多越好;-)! - Sylvester Kruin
4
我认为你不需要每次使用format!宏 - 你可以直接在实际的&str上调用Colorize函数(例如,"Bold".bold()可以代替format!("Bold").bold())。 - iamkneel

55

Rust没有八进制的转义序列。你需要使用十六进制:

println!("\x1b[93mError\x1b[0m");

请参阅https://github.com/rust-lang/rust/issues/30491

发生的事情是,编译器不会报错的原因是在 Rust 中\0 是有效的转义序列,并表示 NULL 字符(ASCII 码为0)。与 C(和 Python)不同的是,Rust 不允许在此之后指定八进制数字。所以它将 33 视为要打印的普通字符。


3
我刚在Clippy中提交了一个问题:https://github.com/rust-lang/rust-clippy/issues/7981 - hellow

1
这对我来说很有效:
cargo add inline_colorization

在main.rs文件中:
use inline_colorization::*;

fn main() {
  println!("Lets the user {color_red}colorize{color_reset} the and {style_underline}style the output{style_reset} text using inline variables");
}

我是提到的rust crate的创建者。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接