Python colorama 库是一个终端文本输出颜色工具
安装
pip install colorama -i http://mirrors.aliyun.com/pypi/simple/ --trusted-host mirrors.aliyun.com
1. 初始化与基本用法
colorama提供了前景色(Fore)、背景色(Back)和样式(Style)三种基本组件,可以组合使用。
from colorama import init, Fore, Back, Style
init()
print(Fore.RED + "这是红色")
print(Fore.RESET + "这是白色")
print(Fore.MAGENTA + "这是紫色")
# 组合使用前景色和背景色
print(Fore.MAGENTA + Back.RED + "紫色文本,红色背景" + Style.RESET_ALL)
# 使用Style重置所有样式
print("这是" + Fore.RED + "红色" + Style.RESET_ALL + "正常颜色")
# 使用Style亮色模式
print(Style.BRIGHT + Fore.YELLOW +"这是亮黄色文本"+ Style.RESET_ALL)
Style.RESET_ALL用于重置所有样式设置,确保后续文本不受影响。
2. 颜色和样式选项
from colorama import Fore, Back, Style
# 前景色选项
fore_colors = [
Fore.BLACK, Fore.RED, Fore.GREEN, Fore.YELLOW,
Fore.BLUE, Fore.MAGENTA, Fore.CYAN, Fore.WHITE,
Fore.LIGHTBLACK_EX, Fore.LIGHTRED_EX, Fore.LIGHTGREEN_EX,
Fore.LIGHTYELLOW_EX, Fore.LIGHTBLUE_EX, Fore.LIGHTMAGENTA_EX,
Fore.LIGHTCYAN_EX, Fore.LIGHTWHITE_EX
]
# 背景色选项
back_colors = [
Back.BLACK, Back.RED, Back.GREEN, Back.YELLOW,
Back.BLUE, Back.MAGENTA, Back.CYAN, Back.WHITE,
Back.LIGHTBLACK_EX, Back.LIGHTRED_EX, Back.LIGHTGREEN_EX,
Back.LIGHTYELLOW_EX, Back.LIGHTBLUE_EX, Back.LIGHTMAGENTA_EX,
Back.LIGHTCYAN_EX, Back.LIGHTWHITE_EX
]
# 样式选项
style_options = [
Style.DIM, Style.NORMAL, Style.BRIGHT
]
# 演示一些组合
print(Fore.RED + "错误消息" + Style.RESET_ALL)
print(Fore.YELLOW + "警告信息" + Style.RESET_ALL)
print(Fore.GREEN + "成功消息" + Style.RESET_ALL)
print(Fore.BLUE + "信息提示" + Style.RESET_ALL)
print(Style.BRIGHT + Fore.RED + "重要错误" + Style.RESET_ALL)
print(Fore.WHITE + Back.RED + "高对比度警告" + Style.RESET_ALL)

3. 自动重置功能
from colorama import init, Fore
# 启用autoreset功能
init(autoreset=True)
# 现在不需要手动重置了
print(Fore.RED + "这行文本是红色的")
print("这行文本自动恢复默认颜色")
print(Fore.GREEN + "绿色文本")
print(Fore.BLUE + "蓝色文本")
print("正常文本")
通过设置autoreset=True,每次打印语句执行后,终端颜色和样式会自动重置为默认值,无需手动添加Style.RESET_ALL。
4.与logging模块一起使用
import logging
from logging.handlers import RotatingFileHandler
from colorama import init, Fore, Style
init(autoreset=True)
class ColoredFormatter(logging.Formatter):
# 创建彩色日志格式化器
COLORS = {
'DEBUG': Fore.BLUE,
'INFO': Fore.GREEN,
'WARNING': Fore.YELLOW,
'ERROR': Fore.RED,
'CRITICAL': Fore.RED + Style.BRIGHT
}
def format(self, record):
log_color = self.COLORS.get(record.levelname, '')
message = super().format(record)
return f"{log_color}{message}{Style.RESET_ALL}"
def create_log():
log = logging.getLogger("ai-ren")
log.setLevel("DEBUG")
fh = RotatingFileHandler(filename='ai-ren-test.log', encoding="utf-8",
maxBytes=1024 * 1024 * 1024, backupCount=10)
fh.setLevel("DEBUG")
# 设置文件处理器的格式化器(不带颜色)
log_format = logging.Formatter('%(asctime)s - [%(filename)s-->line:%(lineno)d]- %(levelname)s:%(message)s')
fh.setFormatter(log_format)
# 设置控制台处理器的格式化器(带颜色)
sh = logging.StreamHandler()
colored_format = ColoredFormatter('%(asctime)s - [%(filename)s-->line:%(lineno)d]- %(levelname)s:%(message)s')
sh.setFormatter(colored_format)
log.addHandler(fh)
log.addHandler(sh)
return log
logger = create_log()
logger.debug("这是一条调试信息")
logger.info("这是一条普通信息")
logger.warning("这是一条警告信息")
logger.error("这是一条错误信息")
logger.critical("这是一条严重错误信息")

5. 对特定平台禁用着色
from colorama import init, Fore
import os
import sys
# 根据环境条件初始化
# strip: 控制是否清除ANSI代码
# convert: 控制是否转换ANSI代码为Win32 API调用
# wrap: 控制是否包装stdout/stderr
# 示例1: 当输出重定向到文件时禁用颜色
is_redirected = not sys.stdout.isatty()
init(strip=is_redirected)
print(Fore.CYAN + "这条信息可能显示为彩色,也可能不会,取决于初始化参数")
# 示例2: 在特定环境变量存在时禁用颜色
if os.environ.get('NO_COLOR'):
init(strip=True)
else:
init()
print(Fore.CYAN + "这条信息可能显示为彩色,也可能不会,取决于初始化参数")
# 示例3: 禁用Windows上的ANSI转换,直接使用ANSI序列
init(convert=True)
# 输出彩色文本
print(Fore.CYAN + "这条信息可能显示为彩色,也可能不会,取决于初始化参数")
6.实际应用场景
在开发命令行工具时,使用不同颜色标识不同操作状态可以大大提高用户体验。以下是一个简单的文件处理工具示例:
from colorama import init, Fore, Style
import time
import os
init(autoreset=True)
def process_files(directory):
"""模拟处理目录中的文件"""
try:
if not os.path.exists(directory):
print(Fore.RED + f"错误:目录'{directory}'不存在")
return False
files = os.listdir(directory)
if not files:
print(Fore.YELLOW + f"警告:目录'{directory}'中没有文件")
return True
print(Fore.BLUE + f"信息:开始处理'{directory}'中的{len(files)}个文件...")
for i, file in enumerate(files, 1):
file_path = os.path.join(directory, file)
if os.path.isfile(file_path):
# 模拟文件处理
print(f"处理文件({i}/{len(files)}):{file}", end='')
for _ in range(3):
time.sleep(0.2)
print(".", end='', flush=True)
print(Fore.GREEN + "完成")
else:
print(Fore.YELLOW + f"跳过目录:{file}")
print(Fore.GREEN + Style.BRIGHT + f"成功: 所有文件处理完毕!")
return True
except Exception as e:
print(Fore.RED + Style.BRIGHT + f"错误:处理失败-{str(e)}")
return False
# 使用示例
process_files("./example")
process_files("../LoveMusic")

浙公网安备 33010602011771号