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


当前回答

我有一个叫做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安装它。

其他回答

这在某种程度上取决于您所在的平台。最常见的方法是打印ANSI转义序列。举个简单的例子,这里有一些来自Blender构建脚本的Python代码:

class bcolors:
    HEADER = '\033[95m'
    OKBLUE = '\033[94m'
    OKCYAN = '\033[96m'
    OKGREEN = '\033[92m'
    WARNING = '\033[93m'
    FAIL = '\033[91m'
    ENDC = '\033[0m'
    BOLD = '\033[1m'
    UNDERLINE = '\033[4m'

要使用这样的代码,可以执行以下操作:

print(bcolors.WARNING + "Warning: No active frommets remain. Continue?" + bcolors.ENDC)

或者,使用Python 3.6+:

print(f"{bcolors.WARNING}Warning: No active frommets remain. Continue?{bcolors.ENDC}")

这将在包括OS X、Linux和Windows在内的UNIX上运行(如果您使用ANSICON,或者在Windows 10中启用VT100仿真)。有用于设置颜色、移动光标等的ANSI代码。

如果你要对此感到复杂(如果你正在编写游戏,这听起来就像是这样),你应该看看“诅咒”模块,它为你处理了很多复杂的部分。Python诅咒HowTO是一个很好的介绍。

如果您不使用扩展ASCII(即,不在PC上),则您只能使用127以下的ASCII字符,而“#”或“@”可能是块的最佳选择。如果您可以确保您的终端使用的是IBM扩展的ASCII字符集,那么您有更多的选项。字符176、177、178和219是“块字符”。

一些基于文本的现代程序,如“矮人堡垒”,以图形模式模拟文本模式,并使用经典PC字体的图像。您可以在矮人要塞Wiki中找到一些位图(用户制作的瓷砖)。

文本模式演示比赛有更多的资源用于在文本模式下制作图形。

作为RGB标准的粉丝,我会这样做:

def color_text(text, rgb):
    r, g, b = rgb
    return f"\033[38;2;{r};{g};{b}m{text}\033[0m"

class rgb():
    BLACK = (0, 0, 0)
    RED = (255, 0, 0)
    GREEN = (0, 255, 0)
    BLUE = (0, 0, 255)
    YELLOW = (255, 255, 0)
    # and so on ...

print(color_text("hello colored world", rgb.GREEN))

PS:受到CircuitSacul回答的强烈启发

基于joeld的答案,使用https://pypi.python.org/pypi/lazyme 管道安装-U lazyme:

from lazyme.string import color_print
>>> color_print('abc')
abc
>>> color_print('abc', color='pink')
abc
>>> color_print('abc', color='red')
abc
>>> color_print('abc', color='yellow')
abc
>>> color_print('abc', color='green')
abc
>>> color_print('abc', color='blue', underline=True)
abc
>>> color_print('abc', color='blue', underline=True, bold=True)
abc
>>> color_print('abc', color='pink', underline=True, bold=True)
abc

截图:


使用新的格式化程序对color_print进行一些更新,例如:

>>> from lazyme.string import palette, highlighter, formatter
>>> from lazyme.string import color_print
>>> palette.keys() # Available colors.
['pink', 'yellow', 'cyan', 'magenta', 'blue', 'gray', 'default', 'black', 'green', 'white', 'red']
>>> highlighter.keys() # Available highlights.
['blue', 'pink', 'gray', 'black', 'yellow', 'cyan', 'green', 'magenta', 'white', 'red']
>>> formatter.keys() # Available formatter,
['hide', 'bold', 'italic', 'default', 'fast_blinking', 'faint', 'strikethrough', 'underline', 'blinking', 'reverse']

注意:斜体、快速闪烁和删除线可能不适用于所有终端,也不适用于Mac和Ubuntu。

例如。,

>>> color_print('foo bar', color='pink', highlight='white')
foo bar
>>> color_print('foo bar', color='pink', highlight='white', reverse=True)
foo bar
>>> color_print('foo bar', color='pink', highlight='white', bold=True)
foo bar
>>> color_print('foo bar', color='pink', highlight='white', faint=True)
foo bar
>>> color_print('foo bar', color='pink', highlight='white', faint=True, reverse=True)
foo bar
>>> color_print('foo bar', color='pink', highlight='white', underline=True, reverse=True)
foo bar

截图:

打印一个开始颜色/样式的字符串,然后是字符串,然后以'\x1b[0m'结束颜色/样式更改:

print('\x1b[6;30;42m' + 'Success!' + '\x1b[0m')

使用以下代码获取shell文本的格式选项表:

def print_format_table():
    """
    prints table of formatted text format options
    """
    for style in range(8):
        for fg in range(30,38):
            s1 = ''
            for bg in range(40,48):
                format = ';'.join([str(style), str(fg), str(bg)])
                s1 += '\x1b[%sm %s \x1b[0m' % (format, format)
            print(s1)
        print('\n')

print_format_table()

亮-暗示例(完整)

暗-亮示例(部分)

参考:https://en.wikipedia.org/wiki/ANSI_escape_code#Colors

这里有一个简单的函数,我使用它来打印彩色文本消息,而不必记住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))