Python
在 Python 中使用 ANSI 转义码
Python 标准库未提供颜色辅助,但你可以直接把 `\x1b` 字节写在字符串里。跨平台场景(1909 之前的 Windows `cmd.exe` 默认不解析 ANSI)请用 `colorama`。如需更丰富的 TUI,`rich` 与 `prompt_toolkit` 都建立在本站记录的字节序列之上。
推荐库
- colorama
跨平台 ANSI 兼容层:在 Windows 上将转义码翻译成 Win32 控制台 API;其他平台则是空操作。模块加载时调用一次 `init()`。
- rich
高级控制台工具集(颜色、表格、进度条、Markdown)。底层仍输出标准 ANSI,自动检测终端能力。
- termcolor
极简的单功能库:`colored('text', 'red', attrs=['bold'])`。无状态、无需初始化,约 150 行代码。
- prompt_toolkit
全屏 TUI 框架 —— REPL(ipython、pgcli)、编辑器、对话框。处理输入解析,包括括号粘贴与鼠标。
常用写法
print('\x1b[1;31merror:\x1b[0m permission denied')from colorama import init, Fore, Style
init() # no-op on POSIX, enables ANSI on legacy Windows
print(f'{Style.BRIGHT}{Fore.RED}error:{Style.RESET_ALL} permission denied')import sys, time
for i in range(101):
# \r returns to col 1, \x1b[K erases to end of line
sys.stdout.write(f'\r\x1b[K{i}%')
sys.stdout.flush()
time.sleep(0.02)
print()import os, sys
USE_COLOR = sys.stdout.isatty() and 'NO_COLOR' not in os.environ
def style(text: str, sgr: str) -> str:
return f'\x1b[{sgr}m{text}\x1b[0m' if USE_COLOR else text
print(style('OK', '32'))