Python的终端彩色输出:termcolor库

termcolor是一个能让终端彩色输出的Python库,通过ANSI转义序列操控文本的颜色、背景色以及样式,比如加粗或下划线等。这个库允许你在终端中以彩色形式输出文本。

 

1、安装:

 pip install termcolor -i https://pypi.mirrors.ustc.edu.cn/simple --trusted-host pypi.mirrors.ustc.edu.cn

 

2、colored 使用方法和参数介绍

参数介绍:

text: 文本(必填)。 

color:文字颜色。可选。常见值:'red''green''yellow' 等。

on_color: 背景色,可选。格式为 `'on_<color>'`,如 `'on_red'`、`'on_blue'`。

attrs:文本属性,可选。如 `['bold']`, `['underline']`, `['reverse']` 。 

from termcolor import colored

print(colored("成功", "green"))
print(colored("警告", "yellow"))
print(colored("错误", "red"))

print(colored("成功", "green", on_color='on_green', attrs=['bold']))

# color支持的颜色
color = [
    "black",
    "grey",
    "red",
    "green",
    "yellow",
    "blue",
    "magenta",
    "cyan",
    "light_grey",
    "dark_grey",
    "light_red",
    "light_green",
    "light_yellow",
    "light_blue",
    "light_magenta",
    "light_cyan",
    "white",
]

# 背景色支持的颜色
on_color = [
    "on_black",
    "on_grey",
    "on_red",
    "on_green",
    "on_yellow",
    "on_blue",
    "on_magenta",
    "on_cyan",
    "on_light_grey",
    "on_dark_grey",
    "on_light_red",
    "on_light_green",
    "on_light_yellow",
    "on_light_blue",
    "on_light_magenta",
    "on_light_cyan",
    "on_white",
]

# 文本属性支持的选项
attrs = [
    "bold",
    "dark",
    "underline",
    "blink",
    "reverse",
    "concealed",
]

 

 

3、cprint使用方法和参数介绍

cpint:是 termcolor 库中的另一个函数,功能与 colored 完全相同,但不会返回字符串,而是直接打印到终端。

参数介绍:
text: 要打印的文本(必填)。 
color:文字颜色。可选。常见值:'red''green''yellow' 等。
on_color: 背景色,可选。格式为 `'on_<color>'`,如 `'on_red'`、`'on_blue'`。
attrs:文本属性,可选。如 `['bold']`, `['underline']`, `['reverse']` 。 
**kwargs:其他关键字参数会传递给内置的 `print()` 函数,比如 `end`、`sep` 等。

案例:

from termcolor import cprint

cprint("Warning!", color="yellow", on_color="on_red", attrs=["bold"], file=sys.stderr)

这段代码会直接打印出黄色加粗文字,红色背景,并输出到标准错误流。 

 

总结对比:

函数名 返回值 是否直接打印
colored 彩色字符串
cprint None

 

posted @ 2025-12-04 10:35  北京测试菜鸟  阅读(17)  评论(0)    收藏  举报