【CanRun】Python终端[颜色文字]输出
【Python搞点好玩的】专栏-直达
简介
在终端中输出彩色文字可以增强用户体验,使重要信息更加突出。Python 提供了多种方式来实现终端颜色输出,但不同操作系统和终端对颜色支持的程度各不相同。
历史发展
- 早期终端 1970s-1980s: 最早的终端如VT52/VT100引入了基本的ANSI转义序列,包括简单的颜色控制
- ANSI标准 1980s: ANSI X3.64标准确立了颜色控制的标准转义序列
- 现代终端 1990s-现在: 终端模拟器广泛支持ANSI颜色,并扩展了256色和真彩色支持
- Windows的演变: 传统cmd.exe不支持ANSI,但Windows 10(TH2)后开始支持,PowerShell和Windows Terminal提供更好支持
主要实现方法
1. ANSI转义序列
python
print("\033[31m红色文字\033[0m")# 红色文字print("\033[1;32m加粗绿色\033[0m")# 加粗绿色
2. colorama库 (跨平台)
python
from colorama import Fore, Back, Style, init
init()# Windows下自动转换ANSI序列print(Fore.RED + "红色文字" + Style.RESET_ALL)
print(Back.GREEN + "绿色背景" + Style.RESET_ALL)
3. termcolor库
python
from termcolor import colored
print(colored('红色文字', 'red'))
print(colored('加粗青色', 'cyan', attrs=['bold']))
4. rich库 (现代高级库)
python
from rich import print
print("[bold red]红色加粗[/bold red]")
print("[#FF5733]自定义颜色[/#FF5733]")
平台兼容性
平台/终端 | ANSI原生支持 | colorama | termcolor | rich | 备注 |
---|---|---|---|---|---|
Linux/macOS终端 | ✓ | ✓ | ✓ | ✓ | 最佳支持 |
Windows cmd(旧版) | ✗ | ✓ | ✓ | ✓ | 需要colorama初始化 |
Windows 10+ cmd | ✓ | ✓ | ✓ | ✓ | 1607版本后原生支持 |
Windows PowerShell | ✓ | ✓ | ✓ | ✓ | 良好支持 |
Windows Terminal | ✓ | ✓ | ✓ | ✓ | 最佳Windows体验 |
Git Bash | ✓ | ✓ | ✓ | ✓ | 表现类似Linux终端 |
旧版macOS Terminal | ✓ | ✓ | ✓ | ✓ | 良好支持 |
嵌入式系统终端 | ✗/部分 | 部分 | 部分 | ✗ | 支持程度不一 |
推荐方案
- 简单跨平台需求: 使用
colorama
+ ANSI基本颜色 - 现代应用开发: 使用
rich
库,提供最丰富的功能 - 服务器/后台应用: 使用
termcolor
或直接ANSI序列(假设Linux环境) - 需要广泛兼容性: 检测平台后选择适当方案,提供无颜色回退
注意事项
- 始终重置颜色样式,避免"颜色泄漏"
- 考虑色盲用户的体验,不要仅依赖颜色传递信息
- 在CI/CD环境中,颜色支持可能不同,应检测是否在TTY中
- 真彩色(24-bit)支持在较新终端中可用,但兼容性不如16色
- 通过合理选择工具和方法,可以在大多数现代平台上实现一致的彩色终端输出体验。
完整示例
以下示例代码在Win上可无序安装三方库直接使用。如需跨平台,可参考以上跨平台库改写cprint()
逻辑。
功能:
- win环境下,调用cprint替代print,在终端输出带颜色的文字(支持cmd;power shell;gitbash)
# coding = "utf-8"
# author = "SmalBox"
# fileName = ColorPrint.pyimport ctypesSTD_INPUT_HANDLE = -10
STD_OUTPUT_HANDLE= -11
STD_ERROR_HANDLE = -12 class FontColor():DarkBlue = 0x01 # FOREGROUND_DARKBLUE 暗蓝色DarkGreen = 0x02 # FOREGROUND_DARKGREEN 暗绿色DarkSkyBlue = 0x03 # FOREGROUND_DARKSKYBLUE 暗天蓝色DarkRed = 0x04 # FOREGROUND_DARKRED 暗红色DarkPink = 0x05 # FOREGROUND_DARKPINK 暗粉红色DarkYellow = 0x06 # FOREGROUND_DARKYELLOW 暗黄色DarkWhite = 0x07 # FOREGROUND_DARKWHITE 暗白色DarkGray = 0x08 # FOREGROUND_DARKGRAY 暗灰色Blue = 0x09 # FOREGROUND_BLUE 蓝色Green = 0x0a # FOREGROUND_GREEN 绿色SkyBlue = 0x0b # FOREGROUND_SKYBLUE 天蓝色Red = 0x0c # FOREGROUND_RED 红色Pink = 0x0d # FOREGROUND_PINK 粉红色Yellow = 0x0e # FOREGROUND_YELLOW 黄色White = 0x0f # FOREGROUND_WHITE 白色stdOutHandle = ctypes.windll.kernel32.GetStdHandle(STD_OUTPUT_HANDLE)def SetCmdTextColor(color:FontColor, handle = stdOutHandle) -> bool:"Set cmd text color"return ctypes.windll.kernel32.SetConsoleTextAttribute(handle, color)def ResetColor() -> None:"Reset text color"SetCmdTextColor(FontColor.DarkWhite)def cprint(text:str, fontColor:FontColor = FontColor.DarkWhite) -> None:"print with color"SetCmdTextColor(fontColor)print(text)ResetColor()if __name__=='__main__':fontColor = FontColor()for item in dir(FontColor):if item[0] != "_":cprint("SmalBox %s"%item, getattr(fontColor, item))
使用样例:
- import导入此脚本,调用cprint即可,参考__main__中的示例
from ColorPrint import *
cprint("SmalBox", FontColor.Pink)
【Python搞点好玩的】专栏-直达
(欢迎点赞留言探讨,更多人加入进来能更加完善这个探索的过程,🙏)