colorama与rich:Python终端颜色输出对比
Python终端彩色输出主要有colorama和rich两种方案。请对比colorama(跨平台ANSI转义码支持)和rich(富文本终端输出)的定位、功能差异,以及sty(轻量级跨平台颜色库)作为第三选择的特点。
回答
编译有声
colorama — 跨平台ANSI颜色支持
from colorama import init, Fore, Back, Style
# Windows下初始化
init(autoreset=True)
print(Fore.RED + '红色文字' + Style.RESET_ALL)
print(Back.GREEN + '绿底文字')
print(Fore.BLUE + Style.BRIGHT + '亮蓝色')
本质:
- 将
\033[31m等ANSI转义码包装为Python常量 - Windows兼容:将ANSI码转为Windows API调用
- 功能单一:仅支持颜色ANSI码(16色 + 背景色 + 样式)
- 轻量级无额外功能
rich — 富文本终端输出
from rich.console import Console
from rich import print as rprint
from rich.table import Table
from rich.markdown import Markdown
from rich.syntax import Syntax
console = Console()
# 颜色+样式
console.print('红色', style='bold red')
console.print('渐变色', style='gradient(red, blue)')
# 表格
table = Table(title='数据')
table.add_column('名称', style='cyan')
table.add_column('值', justify='right')
table.add_row('CPU', '85%')
console.print(table)
# Markdown / 代码 / 日志
console.print(Markdown('# 标题'))
console.print(Syntax('print("hello")', 'python'))
本质:富文本终端渲染引擎,远不止颜色
sty — 轻量级跨平台颜色
from sty import fg, bg, ef, rs
# 类似colorama但更简洁
print(fg.red + '红色' + fg.rs)
print(fg(255, 100, 0) + '24位真彩色' + fg.rs) # 支持RGB
特点:
- 支持24位真彩色
- 无外部依赖
- 跨平台(内部处理Windows)
- 介于colorama和rich之间
对比
| 维度 | colorama | rich | sty |
|---|---|---|---|
| 定位 | ANSI颜色兼容 | 富文本终端 | 轻量颜色库 |
| 颜色支持 | 16色 | 16色+渐变色+256色 | 16色+RGB |
| 表格/日志 | ❌ | ✅ | ❌ |
| 依赖 | 无 | 有 | 无 |
| 安装体积 | 极小 | 较大 | 极小 |
选择:纯颜色→colorama或sty;完整终端UI→rich。