
转载请注明出处:小锋学长生活大爆炸[xfxuezhagn.cn] 如果本文帮助到了你,欢迎[点赞、收藏、关注]哦~
目录
为了方便大家安装,我已经上传到了pypi,因此可以直接通过pip安装了: pip install myprintx

目前只支持颜色输出,后续会陆续添加更多功能。
代码中在输出log时候非常需要通过不同颜色来进行强提醒,比如warn用红色。不想用logging模块,普通的print输出又都是一个颜色,非常不好区分。因此对print进行修改,来支持不同颜色。
def print(
*args,
sep=' ',
end='\n',
file=None,
flush=False,
fg_color=None, # 前景色(文本颜色)
bg_color=None, # 背景色
style=None # 文本样式:'bold'、'underline'、'italic'
):
"""
增强版 print() 函数 —— 支持彩色与样式化终端输出
=======================================================
✅ 功能说明:
该函数在保留 Python 内置 print() 所有功能的基础上,
增加了文本颜色与样式控制能力,可在终端中输出彩色文本,
适合日志、调试信息、高亮提示等场景。
🧩 参数说明:
*args : 任意数量的输出对象,与原生 print 相同。
sep : str, 可选(默认 ' ')
各输出项之间的分隔符。
end : str, 可选(默认 '\n')
输出结束时添加的字符。
file : 文件对象, 可选
指定输出目标(默认 sys.stdout)。
flush : bool, 可选(默认 False)
是否强制刷新输出缓冲区。
fg_color : str, 可选
前景色(文本颜色)。可选值:
['black', 'red', 'green', 'yellow', 'blue', 'purple', 'cyan', 'white']
示例:fg_color='red'
bg_color : str, 可选
背景色。可选值同上,可带或不带前缀 'bg_'。
示例:bg_color='yellow' 或 bg_color='bg_yellow'
style : str, 可选
文本样式。可选值:
- 'bold':加粗
- 'underline':下划线
- 'italic':斜体(部分终端支持)
🎨 示例用法:
print("普通文本")
print("红色文字", fg_color="red")
print("白字红底", fg_color="white", bg_color="red")
print("加粗蓝字", fg_color="blue", style="bold")
print("下划线绿色文字", fg_color="green", style="underline")
print("多参数输出", 123, True, fg_color="cyan", style="italic")
⚙️ 兼容性:
- macOS / Linux 终端:原生支持 ANSI 转义序列
- Windows 10+:自动启用颜色支持
- 写入文件时:颜色代码不会影响文本内容
🧠 原理说明:
通过 ANSI 转义序列控制输出颜色,格式为:
\033[样式;前景色;背景色m 内容 \033[0m
其中 \033[0m 用于重置颜色,避免污染后续输出。
"""
import sys, os
# Windows 环境兼容:启用 ANSI 转义序列支持
if sys.platform == "win32":
os.system("") # 启用颜色支持,对旧版 Windows 也安全
# ANSI 颜色映射表
color_map = {
# 前景色
'black': 30, 'red': 31, 'green': 32, 'yellow': 33,
'blue': 34, 'purple': 35, 'cyan': 36, 'white': 37,
# 背景色
'bg_black': 40, 'bg_red': 41, 'bg_green': 42, 'bg_yellow': 43,
'bg_blue': 44, 'bg_purple': 45, 'bg_cyan': 46, 'bg_white': 47
}
# 文本样式映射表
style_map = {
'bold': 1,
'underline': 4,
'italic': 3
}
# 构建颜色控制码列表
codes = []
# 样式控制
if style and style in style_map:
codes.append(str(style_map[style]))
# 前景色控制
if fg_color:
fg_key = fg_color if fg_color.startswith("fg_") else fg_color
if fg_key in color_map:
codes.append(str(color_map[fg_key]))
elif f"fg_{fg_key}" in color_map:
codes.append(str(color_map[f"fg_{fg_key}"]))
# 背景色控制
if bg_color:
bg_key = bg_color if bg_color.startswith("bg_") else f"bg_{bg_color}"
if bg_key in color_map:
codes.append(str(color_map[bg_key]))
# 构建 ANSI 转义序列
prefix = f"\033[{';'.join(codes)}m" if codes else ''
suffix = "\033[0m" if codes else ''
# 拼接输出文本
text = sep.join(map(str, args))
output = f"{prefix}{text}{suffix}"
# 调用原生 print,避免递归
__builtins__.print(output, sep=sep, end=end, file=file or sys.stdout, flush=flush)
使用示例:
print("正常输出")
print("红色文字", fg_color="red")
print("白字红底", fg_color="white", bg_color="red")
print("加粗蓝字", fg_color="blue", style="bold")
print("下划线绿色文字", fg_color="green", style="underline")
print("多参数输出", 123, True, fg_color="cyan", style="italic")

不改原代码、不每次 import,而是让这个增强版函数直接替代内置 print(),也就是打补丁。Python 内置的 print() 实际上定义在模块 builtins(Python 3)中。因此只要执行以下代码,就可以在全局范围内替换原生 print。之后,无论哪个模块执行 print,都会自动使用增强版版本:
import builtins
builtins.print = <增强版print函数>
import sys, os, builtins
def color_print(
*args,
sep=' ',
end='\n',
file=None,
flush=False,
fg_color=None, # 前景色
bg_color=None, # 背景色
style=None # 样式:bold / underline / italic
):
# 兼容 Windows 终端
if sys.platform == "win32":
os.system("")
color_map = {
# 前景色
'black': 30, 'red': 31, 'green': 32, 'yellow': 33,
'blue': 34, 'purple': 35, 'cyan': 36, 'white': 37,
# 背景色
'bg_black': 40, 'bg_red': 41, 'bg_green': 42, 'bg_yellow': 43,
'bg_blue': 44, 'bg_purple': 45, 'bg_cyan': 46, 'bg_white': 47
}
style_map = {
'bold': 1,
'underline': 4,
'italic': 3
}
codes = []
if style and style in style_map:
codes.append(str(style_map[style]))
if fg_color:
if fg_color in color_map:
codes.append(str(color_map[fg_color]))
elif f"fg_{fg_color}" in color_map:
codes.append(str(color_map[f"fg_{fg_color}"]))
if bg_color:
bg_key = bg_color if bg_color.startswith("bg_") else f"bg_{bg_color}"
if bg_key in color_map:
codes.append(str(color_map[bg_key]))
prefix = f"\033[{';'.join(codes)}m" if codes else ''
suffix = "\033[0m" if codes else ''
text = sep.join(map(str, args))
output = f"{prefix}{text}{suffix}"
builtins.__orig_print__(output, sep=sep, end=end, file=file or sys.stdout, flush=flush)
# -----------------------------
# 🧩 对 print 打补丁(Monkey Patch)
# -----------------------------
if not hasattr(builtins, "__orig_print__"):
builtins.__orig_print__ = builtins.print # 备份原始 print
builtins.print = color_print
把上面代码保存为一个模块,然后在程序入口处只需要执行一次import上述文件,从此以后,全局 print就会自动变彩色,不需要每次都import。
为了方便大家安装,我已经上传到了pypi,因此可以直接通过pip安装了:
pip install myprintx
使用示例:

Python 生态里已经有一些成熟、稳定的库,能让 print() 直接输出彩色文本。
1. colorama
安装:
pip install colorama
示例:
from colorama import Fore, Back, Style, init
init(autoreset=True) # 自动重置颜色(避免污染后续输出)
print(Fore.RED + '红色文字')
print(Fore.GREEN + '绿色文字')
print(Back.YELLOW + Fore.BLACK + '黑字黄底')
print(Style.BRIGHT + Fore.CYAN + '加粗青色')
特点:
pytest、pip 自身)
logging 模块结合
缺点:
print(),而是使用前缀(Fore.RED)样式。
2. termcolor
安装:
pip install termcolor
示例:
from termcolor import colored
print(colored("成功!", "green"))
print(colored("错误!", "red", attrs=["bold"]))
print(colored("警告!", "yellow", "on_red"))
特点:
colored(text, color, on_color, attrs))
bold, underline, reverse
f-string 混用
缺点:
colorama 初始化
3. rich
安装:
pip install rich
示例:
from rich import print
print("[bold red]错误:[/bold red] 无法连接服务器")
print("[green]成功![/green] 已完成操作。")
print("[yellow on blue]提示信息[/yellow on blue]")
特点:
缺点:
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。