在 Python 中有几种方法可以将彩色文本输出到终端。 最常见的做法是:
(1) 使用内置模块
colorama
模块:然后可以使用 Colorama 的 ANSI 转义序列的常量简写来完成彩色文本的跨平台打印:
例一:
# Python program to print
# red text with green background
from colorama import Fore, Back, Style
print(Fore.RED + 'some red text')
print(Back.GREEN + 'and with a green background')
print(Style.DIM + 'and in dim text')
print(Style.RESET_ALL)
print('back to normal now')
结果如下图所示:
例二:
# Python program to print
# green text with red background
from colorama import init
from termcolor import colored
init()
print(colored('Hello, World!', 'green', 'on_red'))
结果如下图所示:
termcolor
模块:termcolor 是一个 Python 模块,用于在终端中输出 ANSII 颜色格式。
# Python program to print
# colored text and background
import sys
from termcolor import colored, cprint
text = colored('Hello, World!', 'red', attrs=['reverse', 'blink'])
print(text)
cprint('Hello, World!'