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


当前回答

一些解决方案包括:

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代码,根据您的选择对输出进行着色(但可能需要调用其他特定于系统的函数,以便能够在终端中显示彩色文本)。

其他回答

答案是Python中所有跨平台着色的Colorama。

它支持Python 3.5+以及Python 2.7。

截至2021 1月,这一数字仍保持不变。

示例代码:

from colorama import init as colorama_init
from colorama import Fore
from colorama import Style

colorama_init()

print(f"This is {Fore.GREEN}color{Style.RESET_ALL}!")

屏幕截图示例:

这是我的现代(2021)解决方案:yachalk

它是少数正确支持嵌套样式的库之一:

除此之外,yachalk是自动完成友好的,具有256/真彩色支持,带有终端功能检测,并且是全类型的。

以下是您在选择解决方案时可能考虑的一些设计决策。

高级库与低级库/手动样式处理?

这个问题的许多答案都演示了如何直接使用ANSI转义代码,或者建议使用需要手动启用/禁用样式的低级库。

这些方法有一些微妙的问题:手动插入打开/关闭样式

语法上更详细,因为必须显式指定重置,更容易出错,因为您可能会意外忘记重置样式,无法正确处理边缘情况:例如,在某些终端中,需要在换行之前重置样式,并在换行后重新激活它们。此外,一些终端在简单地覆盖互斥样式方面存在问题,需要插入“不必要的”重置代码。如果开发者的本地终端没有这些怪癖,开发者不会立即发现这些怪癖。该问题将仅由其他人稍后报告,或导致问题,例如CI终端。

因此,如果要实现与许多终端的兼容性,最好使用提供自动处理样式重置的高级库。这允许库通过在需要时插入“伪”ANSI转义码来处理所有边缘情况。

为什么还有另一个图书馆?

在JavaScript中,任务的实际标准库是粉笔,在JS项目中使用了一段时间后,Python世界中可用的解决方案缺乏可比性。粉笔API不仅使用起来更方便(完全自动完成兼容),它还可以正确处理所有边缘情况。

yachalk的想法是为Python生态系统带来同样的便利。如果您对与其他库的比较感兴趣,我已经在项目页面上开始了功能比较。此外,这里有一长串(但仍然不完整)的备选方案,这些方案是在我的研究中提出的——有很多可供选择:)

有色的安西科色术语颜色科罗拉多州猪圈,猪圈祝福富有的彩色照相机彩色印刷品控制台颜色皮凡奇库勒尔牌手表样式(以前称为clr)皮白垩简单粉笔克洛克白垩质的(古希腊神话中的)古希腊神话

https://raw.github.com/fabric/fabric/master/fabric/colors.py

"""
.. versionadded:: 0.9.2

Functions for wrapping strings in ANSI color codes.

Each function within this module returns the input string ``text``, wrapped
with ANSI color codes for the appropriate color.

For example, to print some text as green on supporting terminals::

    from fabric.colors import green

    print(green("This text is green!"))

Because these functions simply return modified strings, you can nest them::

    from fabric.colors import red, green

    print(red("This sentence is red, except for " + \
          green("these words, which are green") + "."))

If ``bold`` is set to ``True``, the ANSI flag for bolding will be flipped on
for that particular invocation, which usually shows up as a bold or brighter
version of the original color on most terminals.
"""


def _wrap_with(code):

    def inner(text, bold=False):
        c = code
        if bold:
            c = "1;%s" % c
        return "\033[%sm%s\033[0m" % (c, text)
    return inner

red = _wrap_with('31')
green = _wrap_with('32')
yellow = _wrap_with('33')
blue = _wrap_with('34')
magenta = _wrap_with('35')
cyan = _wrap_with('36')
white = _wrap_with('37')

耶!另一个版本

虽然我觉得这个答案很有用,但我做了一些修改。此GitHub Gist是结果

用法

print colors.draw("i'm yellow", bold=True, fg_yellow=True)

此外,还可以包装常用用法:

print colors.error('sorry, ')

https://gist.github.com/Jossef/0ee20314577925b4027f

我能找到的最简单的方法不是使用ANSI转义码,而是使用导入模块colorama中的Fore。看看下面的代码:

from colorama import Fore, Style

print(Fore.MAGENTA + "IZZ MAGENTA BRUH.")

print(Style.RESET_ALL + "IZZ BACK TO NORMALZ.")

与ANSI转义码相比:

print("\u001b[31m IZZ RED (NO MAGENTA ON ANSI CODES).\u001b[0m")

print("BACK TO NORMALZ.")