如何使用 Rust 将彩色文本输出到终端?我尝试使用在this python answer中找到的特殊转义字符,但它们只是按字面打印。这是我的代码:
fn main() {
println!("\033[93mError\033[0m");
}
欢迎任何见解!
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()
);
}
示例颜色输出:
每个格式函数(
red()
、italics()
等)都可以单独使用,也可以与其他函数结合使用。但如果您相互组合使用颜色,则仅显示最后设置的颜色。
Rust 没有八进制转义序列。您必须使用十六进制:
println!("\x1b[93mError\x1b[0m");
另请参阅 https://github.com/rust-lang/rust/issues/30491。
发生了什么,也是编译器没有抱怨的原因,是
\0
是 Rust 中的一个有效的转义序列 - 代表 NULL 字符(ASCII 代码 0)。只是 Rust 与 C(和 Python)不同,不允许您在此之后指定八进制数。因此它认为 33
是要打印的普通字符。
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");
}