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


当前回答

sty类似于colorama,但它不那么冗长,支持8位和24位(RGB)颜色,支持所有效果(粗体、下划线等),允许您注册自己的样式,是完全类型和高性能的,支持静音,不干扰全局设置,如sys.stdout,真的很灵活,文档很好,等等。。。

示例:

from sty import fg, bg, ef, rs

foo = fg.red + 'This is red text!' + fg.rs
bar = bg.blue + 'This has a blue background!' + bg.rs
baz = ef.italic + 'This is italic text' + rs.italic
qux = fg(201) + 'This is pink text using 8bit colors' + fg.rs
qui = fg(255, 10, 10) + 'This is red text using 24bit colors.' + fg.rs

# Add custom colors:

from sty import Style, RgbFg

fg.orange = Style(RgbFg(255, 150, 50))

buf = fg.orange + 'Yay, Im orange.' + fg.rs

print(foo, bar, baz, qux, qui, buf, sep='\n')

打印:

演示:

其他回答

这里有一个快速类,它包装了一个打印功能,可以快速添加颜色,而无需安装其他软件包。

class PrintColored:
    DEFAULT = '\033[0m'
    # Styles
    BOLD = '\033[1m'
    ITALIC = '\033[3m'
    UNDERLINE = '\033[4m'
    UNDERLINE_THICK = '\033[21m'
    HIGHLIGHTED = '\033[7m'
    HIGHLIGHTED_BLACK = '\033[40m'
    HIGHLIGHTED_RED = '\033[41m'
    HIGHLIGHTED_GREEN = '\033[42m'
    HIGHLIGHTED_YELLOW = '\033[43m'
    HIGHLIGHTED_BLUE = '\033[44m'
    HIGHLIGHTED_PURPLE = '\033[45m'
    HIGHLIGHTED_CYAN = '\033[46m'
    HIGHLIGHTED_GREY = '\033[47m'

    HIGHLIGHTED_GREY_LIGHT = '\033[100m'
    HIGHLIGHTED_RED_LIGHT = '\033[101m'
    HIGHLIGHTED_GREEN_LIGHT = '\033[102m'
    HIGHLIGHTED_YELLOW_LIGHT = '\033[103m'
    HIGHLIGHTED_BLUE_LIGHT = '\033[104m'
    HIGHLIGHTED_PURPLE_LIGHT = '\033[105m'
    HIGHLIGHTED_CYAN_LIGHT = '\033[106m'
    HIGHLIGHTED_WHITE_LIGHT = '\033[107m'

    STRIKE_THROUGH = '\033[9m'
    MARGIN_1 = '\033[51m'
    MARGIN_2 = '\033[52m' # seems equal to MARGIN_1
    # colors
    BLACK = '\033[30m'
    RED_DARK = '\033[31m'
    GREEN_DARK = '\033[32m'
    YELLOW_DARK = '\033[33m'
    BLUE_DARK = '\033[34m'
    PURPLE_DARK = '\033[35m'
    CYAN_DARK = '\033[36m'
    GREY_DARK = '\033[37m'

    BLACK_LIGHT = '\033[90m'
    RED = '\033[91m'
    GREEN = '\033[92m'
    YELLOW = '\033[93m'
    BLUE = '\033[94m'
    PURPLE = '\033[95m'
    CYAN = '\033[96m'
    WHITE = '\033[96m'

    def __init__(self):
        self.print_original = print # old value to the original print function
        self.current_color = self.DEFAULT

    def __call__(self,
                 *values: object, sep: str | None = None,
                 end: str | None = None,
                 file: str | None = None,
                 flush: bool = False,
                 color: str|None = None,
                 default_color: str|None = None,
    ):
        if default_color:
            self.current_color = default_color

        default = self.current_color
        if color:
            values = (color, *values, default)  # wrap the content within a selected color an a default
        else:
            values = (*values, default)  # wrap the content within a selected color an a default
        self.print_original(*values, end=end, file=file, flush=flush)

用法

class PrintColored:
    DEFAULT = '\033[0m'
    # Styles
    BOLD = '\033[1m'
    ITALIC = '\033[3m'
    UNDERLINE = '\033[4m'
    UNDERLINE_THICK = '\033[21m'
    HIGHLIGHTED = '\033[7m'
    HIGHLIGHTED_BLACK = '\033[40m'
    HIGHLIGHTED_RED = '\033[41m'
    HIGHLIGHTED_GREEN = '\033[42m'
    HIGHLIGHTED_YELLOW = '\033[43m'
    HIGHLIGHTED_BLUE = '\033[44m'
    HIGHLIGHTED_PURPLE = '\033[45m'
    HIGHLIGHTED_CYAN = '\033[46m'
    HIGHLIGHTED_GREY = '\033[47m'

    HIGHLIGHTED_GREY_LIGHT = '\033[100m'
    HIGHLIGHTED_RED_LIGHT = '\033[101m'
    HIGHLIGHTED_GREEN_LIGHT = '\033[102m'
    HIGHLIGHTED_YELLOW_LIGHT = '\033[103m'
    HIGHLIGHTED_BLUE_LIGHT = '\033[104m'
    HIGHLIGHTED_PURPLE_LIGHT = '\033[105m'
    HIGHLIGHTED_CYAN_LIGHT = '\033[106m'
    HIGHLIGHTED_WHITE_LIGHT = '\033[107m'

    STRIKE_THROUGH = '\033[9m'
    MARGIN_1 = '\033[51m'
    MARGIN_2 = '\033[52m' # seems equal to MARGIN_1
    # colors
    BLACK = '\033[30m'
    RED_DARK = '\033[31m'
    GREEN_DARK = '\033[32m'
    YELLOW_DARK = '\033[33m'
    BLUE_DARK = '\033[34m'
    PURPLE_DARK = '\033[35m'
    CYAN_DARK = '\033[36m'
    GREY_DARK = '\033[37m'

    BLACK_LIGHT = '\033[90m'
    RED = '\033[91m'
    GREEN = '\033[92m'
    YELLOW = '\033[93m'
    BLUE = '\033[94m'
    PURPLE = '\033[95m'
    CYAN = '\033[96m'
    WHITE = '\033[96m'

    def __init__(self):
        self.print_original = print # old value to the original print function
        self.current_color = self.DEFAULT

    def __call__(self,
                 *values: object, sep: str | None = None,
                 end: str | None = None,
                 file: str | None = None,
                 flush: bool = False,
                 color: str|None = None,
                 default_color: str|None = None,
    ):
        if default_color:
            self.current_color = default_color

        default = self.current_color
        if color:
            values = (color, *values, default)  # wrap the content within a selected color an a default
        else:
            values = (*values, default)  # wrap the content within a selected color an a default
        self.print_original(*values, end=end, file=file, flush=flush)

if __name__ == '__main__':
    print = PrintColored()

    print("Hello world - default")
    print("Hello world - Bold", color=print.BOLD)
    print("Hello world - Italic", color=print.ITALIC)
    print("Hello world - Underline", color=print.UNDERLINE)
    print("Hello world - UNDERLINE_THICK", color=print.UNDERLINE_THICK)
    print("Hello world - HighLithted", color=print.HIGHLIGHTED)
    print("Hello world - HIGHLIGHTED_BLACK", color=print.HIGHLIGHTED_BLACK)
    print("Hello world - HIGHLIGHTED_RED", color=print.HIGHLIGHTED_RED)
    print("Hello world - HIGHLIGHTED_GREEN", color=print.HIGHLIGHTED_GREEN)
    print("Hello world - HIGHLIGHTED_YELLOW", color=print.HIGHLIGHTED_YELLOW)
    print("Hello world - HIGHLIGHTED_BLUE", color=print.HIGHLIGHTED_BLUE)
    print("Hello world - HIGHLIGHTED_PURPLE", color=print.HIGHLIGHTED_PURPLE)
    print("Hello world - HIGHLIGHTED_CYAN", color=print.HIGHLIGHTED_CYAN)
    print("Hello world - HIGHLIGHTED_GREY", color=print.HIGHLIGHTED_GREY)
    print("Hello world - HIGHLIGHTED_GREY_LIGHT", color=print.HIGHLIGHTED_GREY_LIGHT)
    print("Hello world - HIGHLIGHTED_RED_LIGHT", color=print.HIGHLIGHTED_RED_LIGHT)
    print("Hello world - HIGHLIGHTED_GREEN_LIGHT", color=print.HIGHLIGHTED_GREEN_LIGHT)
    print("Hello world - HIGHLIGHTED_YELLOW_LIGHT", color=print.HIGHLIGHTED_YELLOW_LIGHT)
    print("Hello world - HIGHLIGHTED_BLUE_LIGHT", color=print.HIGHLIGHTED_BLUE_LIGHT)
    print("Hello world - HIGHLIGHTED_PURPLE_LIGHT", color=print.HIGHLIGHTED_PURPLE_LIGHT)
    print("Hello world - HIGHLIGHTED_CYAN_LIGHT", color=print.HIGHLIGHTED_CYAN_LIGHT)
    print("Hello world - HIGHLIGHTED_WHITE_LIGHT", color=print.HIGHLIGHTED_WHITE_LIGHT)
    print("Hello world - STRIKE_THROUGH", color=print.STRIKE_THROUGH)
    print("Hello world - MARGIN_1", color=print.MARGIN_1)
    print("Hello world - MARGIN_2", color=print.MARGIN_2)

    print("Hello world - BLACK", color=print.BLACK)
    print("Hello world - RED_DARK", color=print.RED_DARK)
    print("Hello world - GREEN_DARK", color=print.GREEN_DARK)
    print("Hello world - YELLOW_DARK", color=print.YELLOW_DARK)
    print("Hello world - BLUE_DARK", color=print.BLUE_DARK)
    print("Hello world - PURPLE_DARK", color=print.PURPLE_DARK)
    print("Hello world - CYAN_DARK", color=print.CYAN_DARK)
    print("Hello world - GREY_DARK", color=print.GREY_DARK)
    print("Hello world - BLACK_LIGHT", color=print.BLACK_LIGHT)
    print("Hello world - BLACK_LIGHT", color=print.BLACK_LIGHT)
    print("Hello world - RED", color=print.RED)
    print("Hello world - GREEN", color=print.GREEN)
    print("Hello world - YELLOW", color=print.YELLOW)
    print("Hello world - BLUE", color=print.BLUE)
    print("Hello world - PURPLE", color=print.PURPLE)
    print("Hello world - CYAN", color=print.CYAN)
    print("Hello world - WHITE", color=print.WHITE)

    # Back to normal
    print("", default_color=print.DEFAULT)
    print("Hello world - default")


输出

您可以使用curses库的Python实现:curses-字符单元显示的终端处理

此外,运行此程序,您将找到您的盒子:

for i in range(255):
    print i, chr(i)

还有Python termcolor模块。用法很简单:

from termcolor import colored

print colored('hello', 'red'), colored('world', 'green')

或者在Python 3中:

print(colored('hello', 'red'), colored('world', 'green'))

然而,对于游戏编程和你想做的“彩色方块”来说,它可能不够复杂。。。

要使ANSI代码在windows上运行,请首先运行

os.system('color')

这里有一个本机适用于Windows 10的解决方案。

使用系统调用,如os.system(“”),允许在命令提示符和Powershell中以本机方式打印颜色:

import os

# System call
os.system("")

# Class of different styles
class style():
    BLACK = '\033[30m'
    RED = '\033[31m'
    GREEN = '\033[32m'
    YELLOW = '\033[33m'
    BLUE = '\033[34m'
    MAGENTA = '\033[35m'
    CYAN = '\033[36m'
    WHITE = '\033[37m'
    UNDERLINE = '\033[4m'
    RESET = '\033[0m'

print(style.YELLOW + "Hello, World!")

注意:Windows不完全支持ANSI代码,无论是通过系统调用还是模块。并非所有的文字装饰都受支持,虽然显示的是明亮的颜色,但它们与常规颜色相同。

感谢@j-l找到了更短的方法。

tl;dr:添加os.system(“”)

如果您使用的是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 ... ")