Colorama:Python终端色彩美化从入门到高级
入门篇:基础使用
Colorama是一个Python库,用于在Windows/Linux/macOS终端输出彩色文本:
from colorama import init, Fore, Back, Style# 初始化(Windows必需)
init()print(Fore.RED + '红色文字' + Style.RESET_ALL)
print(Back.GREEN + '绿色背景' + Style.RESET_ALL)
print(Style.BRIGHT + '加粗文字' + Style.RESET_ALL)
基本颜色:
• Fore
: 前景色(文字颜色)
• Back
: 背景色
• Style
: 样式(加粗/暗淡等)
进阶篇:实用技巧
- 自动重置样式:使用
autoreset=True
避免手动重置
init(autoreset=True)
print(Fore.BLUE + '自动重置的蓝色文字')
- 组合样式:
print(Fore.YELLOW + Back.BLUE + Style.BRIGHT + '组合样式')
- 跨平台兼容:
init(strip=False) # 强制保留ANSI代码(即使重定向到文件)
高级篇:实际应用
- 日志分级着色:
def log_error(msg): print(Fore.RED + "[ERROR] " + msg)
def log_warn(msg): print(Fore.YELLOW + "[WARN] " + msg)
- 进度条美化:
for i in range(100):print(f"\r{Fore.CYAN}进度: {i}%", end="")
- 表格输出:
data = [["Item", "Status"], ["A", "OK"], ["B", "FAIL"]]
for row in data:color = Fore.GREEN if row[1] == "OK" else Fore.REDprint(f"{row[0]:<10}{color}{row[1]}")
注意事项
• 始终在程序结束时调用deinit()
(或使用with
上下文)
• 考虑色盲用户的体验,不要仅靠颜色传递关键信息
• 在CI/CD环境中可能需要禁用颜色输出
Colorama让终端输出更专业直观,是开发命令行工具的必备利器!