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


当前回答

根据乔尔德的回答,这简直太简单了:

class PrintInColor:
    RED = '\033[91m'
    GREEN = '\033[92m'
    YELLOW = '\033[93m'
    LIGHT_PURPLE = '\033[94m'
    PURPLE = '\033[95m'
    END = '\033[0m'

    @classmethod
    def red(cls, s, **kwargs):
        print(cls.RED + s + cls.END, **kwargs)

    @classmethod
    def green(cls, s, **kwargs):
        print(cls.GREEN + s + cls.END, **kwargs)

    @classmethod
    def yellow(cls, s, **kwargs):
        print(cls.YELLOW + s + cls.END, **kwargs)

    @classmethod
    def lightPurple(cls, s, **kwargs):
        print(cls.LIGHT_PURPLE + s + cls.END, **kwargs)

    @classmethod
    def purple(cls, s, **kwargs):
        print(cls.PURPLE + s + cls.END, **kwargs)

那么就

PrintInColor.red('hello', end=' ')
PrintInColor.green('world')

其他回答

我是Python新手,每次我发现像这样的主题时都很兴奋。但这次(突然)我觉得我有话要说。尤其是因为几分钟前,我在Python中发现了一件令人惊叹的事情(至少对我来说是这样):

上下文管理器

from contextlib import contextmanager
# FORECOLOR
BLACKFC,REDFC,GREENFC,YELLOWFC,BLUEFC = '38;30m','38;31m','38;32m','38;33m','38;34m'
# BACKGOUND
BLACKBG,REDBG,GREENBG,YELLOWBG,BLUEBG = '48;40m','48;41m','48;42m','48;43m','48;44m'

@contextmanager
def printESC(prefix, color, text):
  print("{prefix}{color}{text}".format(prefix=prefix, color=color, text=text), end='')
  yield
  print("{prefix}0m".format(prefix=prefix))

with printESC('\x1B[', REDFC, 'Colored Text'):
  pass

实例

或者就像这样:

# FORECOLOR
BLACKFC,REDFC,GREENFC,YELLOWFC,BLUEFC = '38;30m','38;31m','38;32m','38;33m','38;34m'
# BACKGOUND
BLACKBG,REDBG,GREENBG,YELLOWBG,BLUEBG = '48;40m','48;41m','48;42m','48;43m','48;44m'

def printESC(prefix, color, text):
  print("{prefix}{color}{text}".format(prefix=prefix, color=color, text=text), end='')
  print("{prefix}0m".format(prefix=prefix))

printESC('\x1B[', REDFC, 'Colored Text')
import click

click.secho('Hello, World!', fg='green')
click.secho('Some more text', bg='blue', fg='white')
click.secho('ATTENTION', blink=True, bold=True)

click(CLI库)有一种非常方便的方式来实现这一点,如果您正在编写命令行工具,无论如何都值得考虑。

我最喜欢的方式是使用祝福库(完整披露:我写的)。例如:

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颜色的终端。它还将不可读的转义序列排除在代码之外,同时保持使用简洁。玩得高兴

另一个包装Python3打印功能的PyPI模块:

https://pypi.python.org/pypi/colorprint

如果您也可以从__future_import-print中使用,它可以在Python2.x中使用。下面是模块PyPI页面中的Python 2示例:

from __future__ import print_function
from colorprint import *

print('Hello', 'world', color='blue', end='', sep=', ')
print('!', color='red', format=['bold', 'blink'])

它输出“你好,世界!”,单词为蓝色,感叹号为粗体红色并闪烁。

这里有一个简单的函数,我使用它来打印彩色文本消息,而不必记住ANSI代码,而是使用标准RGB元组来定义前景和背景颜色。

def print_in_color(txt_msg, fore_tuple, back_tuple, ):
    # Prints the text_msg in the foreground color specified by fore_tuple with the background specified by back_tuple
    # text_msg is the text, fore_tuple is foreground color tuple (r,g,b), back_tuple is background tuple (r,g,b)
    rf,bf,gf = fore_tuple
    rb,gb,bb = back_tuple
    msg = '{0}' + txt_msg
    mat = '\33[38;2;' + str(rf) + ';' + str(gf) + ';' + str(bf) + ';48;2;' + str(rb) + ';' +str(gb) + ';' + str(bb) + 'm'
    print(msg .format(mat))
    print('\33[0m') # Returns default print color to back to black

# Example of use using a message with variables
fore_color = 'cyan'
back_color = 'dark green'
msg = 'foreground color is {0} and the background color is {1}'.format(fore_color, back_color)
print_in_color(msg, (0,255,255), (0,127,127))