如何在Python中将彩色文本输出到终端?
当前回答
我编写了一个在PyPI上可用的库,它有一个遵循标准打印函数的简单API。
你可以用pip安装着色来安装它。
import coloring
# Directly use print-like functions
coloring.print_red('Hello', 12)
coloring.print_green('Hey', end="", sep=";")
print()
# Get str as return
print(coloring.red('hello'))
# Use the generic colorize function
print(coloring.colorize("I'm red", "red")) # Using color names
print(coloring.colorize("I'm green", (0, 255, 0))) # Using RGB colors
print(coloring.colorize("I'm blue", "#0000ff")) # Using hex colors
# Or using styles (underline, bold, italic, ...)
print(coloring.colorize('Hello', 'red', s='ub')) # underline and bold
执行代码:
您可以在此处查看所有功能:https://github.com/Nazime/coloring.
其他回答
这是我的现代(2021)解决方案:yachalk
它是少数正确支持嵌套样式的库之一:
除此之外,yachalk是自动完成友好的,具有256/真彩色支持,带有终端功能检测,并且是全类型的。
以下是您在选择解决方案时可能考虑的一些设计决策。
高级库与低级库/手动样式处理?
这个问题的许多答案都演示了如何直接使用ANSI转义代码,或者建议使用需要手动启用/禁用样式的低级库。
这些方法有一些微妙的问题:手动插入打开/关闭样式
语法上更详细,因为必须显式指定重置,更容易出错,因为您可能会意外忘记重置样式,无法正确处理边缘情况:例如,在某些终端中,需要在换行之前重置样式,并在换行后重新激活它们。此外,一些终端在简单地覆盖互斥样式方面存在问题,需要插入“不必要的”重置代码。如果开发者的本地终端没有这些怪癖,开发者不会立即发现这些怪癖。该问题将仅由其他人稍后报告,或导致问题,例如CI终端。
因此,如果要实现与许多终端的兼容性,最好使用提供自动处理样式重置的高级库。这允许库通过在需要时插入“伪”ANSI转义码来处理所有边缘情况。
为什么还有另一个图书馆?
在JavaScript中,任务的实际标准库是粉笔,在JS项目中使用了一段时间后,Python世界中可用的解决方案缺乏可比性。粉笔API不仅使用起来更方便(完全自动完成兼容),它还可以正确处理所有边缘情况。
yachalk的想法是为Python生态系统带来同样的便利。如果您对与其他库的比较感兴趣,我已经在项目页面上开始了功能比较。此外,这里有一长串(但仍然不完整)的备选方案,这些方案是在我的研究中提出的——有很多可供选择:)
有色的安西科色术语颜色科罗拉多州猪圈,猪圈祝福富有的彩色照相机彩色印刷品控制台颜色皮凡奇库勒尔牌手表样式(以前称为clr)皮白垩简单粉笔克洛克白垩质的(古希腊神话中的)古希腊神话
对于Windows,除非使用Win32 API,否则无法使用颜色打印到控制台。
对于Linux,它就像使用打印一样简单,转义序列如下:
颜色
要使字符像方框一样打印,这实际上取决于控制台窗口使用的字体。磅符号效果很好,但它取决于字体:
#
一些解决方案包括:
fg = lambda text, color: "\33[38;5;" + str(color) + "m" + text + "\33[0m"
bg = lambda text, color: "\33[48;5;" + str(color) + "m" + text + "\33[0m"
def print_six(row, format, end="\n"):
for col in range(6):
color = row*6 + col - 2
if color>=0:
text = "{:3d}".format(color)
print (format(text,color), end=" ")
else:
print(end=" ") # Four spaces
print(end=end)
for row in range(0, 43):
print_six(row, fg, " ")
print_six(row, bg)
print(fg("text", 160))
OR
def colored(r, g, b, text):
return "\033[38;2;{};{};{}m{} \033[38;2;255;255;255m".format(r, g, b, text)
text = 'Hello, World!'
colored_text = colored(255, 0, 0, text)
print(colored_text)
OR
class Color:
COLOR = [f"\33[{i}m" for i in range(44)]
for i in range(44):
print(Color.COLOR[i] + 'text')
可能无法在Windows 10终端或PowerShell窗口上运行,或者在其他情况下可能无法直接运行。
但在插入时,程序开头的这两行可能会有所帮助:
import os
os.system('')
os.system(“”)允许您在终端中打印ANSI代码,根据您的选择对输出进行着色(但可能需要调用其他特定于系统的函数,以便能够在终端中显示彩色文本)。
我最喜欢的方式是使用祝福库(完整披露:我写的)。例如:
from blessings import Terminal
t = Terminal()
print t.red('This is red.')
print t.bold_bright_red_on_black('Bright red on black')
要打印彩色砖,最可靠的方法是使用背景色打印空间。我使用此技术绘制鼻子进度条:
print t.on_green(' ')
您还可以在特定位置打印:
with t.location(0, 5):
print t.on_yellow(' ')
如果你必须在游戏过程中使用其他终端功能,你也可以这样做。您可以使用Python的标准字符串格式来保持其可读性:
print '{t.clear_eol}You just cleared a {t.bold}whole{t.normal} line!'.format(t=t)
Blessings的优点在于它能在各种终端上工作,而不仅仅是ANSI颜色的终端。它还将不可读的转义序列排除在代码之外,同时保持使用简洁。玩得高兴
我有一个叫做colorist的图书馆。这非常简单。
以下是一些示例:
from colorit import *
# Use this to ensure that ColorIt will be usable by certain command line interfaces
# Note: This clears the terminal
init_colorit()
# Foreground
print(color("This text is red", Colors.red))
print(color("This text is orange", Colors.orange))
print(color("This text is yellow", Colors.yellow))
print(color("This text is green", Colors.green))
print(color("This text is blue", Colors.blue))
print(color("This text is purple", Colors.purple))
print(color("This text is white", Colors.white))
# Background
print(background("This text has a background that is red", Colors.red))
print(background("This text has a background that is orange", Colors.orange))
print(background("This text has a background that is yellow", Colors.yellow))
print(background("This text has a background that is green", Colors.green))
print(background("This text has a background that is blue", Colors.blue))
print(background("This text has a background that is purple", Colors.purple))
print(background("This text has a background that is white", Colors.white))
# Custom
print(color("This color has a custom grey text color", (150, 150, 150)))
print(background("This color has a custom grey background", (150, 150, 150)))
# Combination
print(
background(
color("This text is blue with a white background", Colors.blue), Colors.white
)
)
# If you are using Windows Command Line, this is so that it doesn't close immediately
input()
这为您提供了:
值得注意的是,这是跨平台的,已经在Mac、Linux和Windows上进行了测试。
你可能想试试:https://github.com/SuperMaZingCoder/colorit
coloret现在可以与PyPi一起安装了!您可以在Windows上使用pipinstall-color-it安装它,在macOS和Linux上使用pip3 install-color-it安装它。