如何在Python中将彩色文本输出到终端?


当前回答

我编写了一个在Linux、OS X和Windows中处理颜色的模块。它支持所有平台上的所有16种颜色,您可以在不同的时间设置前景和背景颜色,字符串对象可以为len()和.capitalize()等对象提供正常的结果。

https://github.com/Robpol86/colorclass

其他回答

我的两分钱(PyColorTerm):

安装:

sudo apt-get install python-pip
pip install pycolorterm

Python脚本:

from pycolorterm import pycolorterm

with pycolorterm.pretty_output(pycolorterm.FG_GREEN) as out:
    out.write('Works OK!')

“工作正常!”显示为绿色。

Rich是一个相对较新的Python库,用于在终端中处理颜色。

在Rich中有几种处理颜色的方法。最快的入门方法是富打印方法,它将类似BBCode的语法呈现到ANSI控制代码中:

from rich import print
print("[red]Color[/] in the [bold magenta]Terminal[/]!")

还有其他方法可以通过Rich(正则表达式、语法)和相关的格式化功能应用颜色。

如果您使用的是Windows,那么就在这里!

# Display text on a Windows console
# Windows XP with Python 2.7 or Python 3.2
from ctypes import windll

# Needed for Python2/Python3 diff
try:
    input = raw_input
except:
    pass
STD_OUTPUT_HANDLE = -11
stdout_handle = windll.kernel32.GetStdHandle(STD_OUTPUT_HANDLE)
# Look at the output and select the color you want.
# For instance, hex E is yellow on black.
# Hex 1E is yellow on blue.
# Hex 2E is yellow on green and so on.
for color in range(0, 75):
     windll.kernel32.SetConsoleTextAttribute(stdout_handle, color)
     print("%X --> %s" % (color, "Have a fine day!"))
     input("Press Enter to go on ... ")

您可以使用pygments模块来执行此操作。例如:

from pygments import console
print(pygments.console.colorize("red", "This text is red."))

这不允许您为终端提供十六进制颜色,但您可以尝试许多内置颜色,如“蓝色”、“深绿色”、“黄色”等。

为了解决这个问题,我创建了一个简单得让人麻木的程序包,用插值颜色代码打印字符串,称为icolor。

icolor包含两个函数:cformat和cprint,每个函数都包含一个字符串和子字符串,这些子字符串被插值以映射到ANSI转义序列。

from icolor import cformat # there is also cprint

cformat("This is #RED;a red string, partially with a #xBLUE;blue background")
'This is \x1b[31ma red string, partially with a \x1b[44mblue background\x1b[0m'

包括所有ANSI颜色(例如#RED;、#BLUE;等)以及#RESET#粗体;以及其他。

背景色具有x前缀,因此绿色背景将为#xGREEN;。

一个人可以用##逃脱#。

鉴于其简单性,最好的文档可能是代码本身。

它在PYPI上,因此可以使用sudo easy_install icolor。