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


当前回答

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

其他回答

对于字符

您的终端很可能使用Unicode(通常为UTF-8编码)字符,所以只需选择合适的字体即可看到您喜爱的字符。Unicode字符U+2588,“完整块”是我建议您使用的字符。

尝试以下操作:

import unicodedata
fp= open("character_list", "w")
for index in xrange(65536):
    char= unichr(index)
    try: its_name= unicodedata.name(char)
    except ValueError: its_name= "N/A"
    fp.write("%05d %04x %s %s\n" % (index, index, char.encode("UTF-8"), its_name)
fp.close()

稍后使用您喜爱的查看器检查文件。

对于颜色

curses是您要使用的模块。查看本教程。

定义开始颜色的字符串和结束颜色的字符串。然后打印文本,开始字符串在前面,结束字符串在结尾。

CRED = '\033[91m'
CEND = '\033[0m'
print(CRED + "Error, does not compute!" + CEND)

这将在Bash和urxvt中使用Zenburn风格的配色方案生成以下内容:

通过实验,我们可以获得更多的颜色:

注意:\33[5m和\33[6m闪烁。

这样我们可以创建一个完整的颜色集合:

CEND      = '\33[0m'
CBOLD     = '\33[1m'
CITALIC   = '\33[3m'
CURL      = '\33[4m'
CBLINK    = '\33[5m'
CBLINK2   = '\33[6m'
CSELECTED = '\33[7m'

CBLACK  = '\33[30m'
CRED    = '\33[31m'
CGREEN  = '\33[32m'
CYELLOW = '\33[33m'
CBLUE   = '\33[34m'
CVIOLET = '\33[35m'
CBEIGE  = '\33[36m'
CWHITE  = '\33[37m'

CBLACKBG  = '\33[40m'
CREDBG    = '\33[41m'
CGREENBG  = '\33[42m'
CYELLOWBG = '\33[43m'
CBLUEBG   = '\33[44m'
CVIOLETBG = '\33[45m'
CBEIGEBG  = '\33[46m'
CWHITEBG  = '\33[47m'

CGREY    = '\33[90m'
CRED2    = '\33[91m'
CGREEN2  = '\33[92m'
CYELLOW2 = '\33[93m'
CBLUE2   = '\33[94m'
CVIOLET2 = '\33[95m'
CBEIGE2  = '\33[96m'
CWHITE2  = '\33[97m'

CGREYBG    = '\33[100m'
CREDBG2    = '\33[101m'
CGREENBG2  = '\33[102m'
CYELLOWBG2 = '\33[103m'
CBLUEBG2   = '\33[104m'
CVIOLETBG2 = '\33[105m'
CBEIGEBG2  = '\33[106m'
CWHITEBG2  = '\33[107m'

以下是生成测试的代码:

x = 0
for i in range(24):
  colors = ""
  for j in range(5):
    code = str(x+j)
    colors = colors + "\33[" + code + "m\\33[" + code + "m\033[0m "
  print(colors)
  x = x + 5
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库)有一种非常方便的方式来实现这一点,如果您正在编写命令行工具,无论如何都值得考虑。

这个答案试图通过使用正则表达式为文本块中的关键字着色来扩展将着色文本写入终端的概念。

这个答案还使用了Python库Rich,在前面的问题答案中简要介绍了它。在这个答案中,我使用函数rich.color.ANSI_color_NAMES获取一个随机的颜色列表,用于突出显示预定义的搜索项。

import random
import re as regex
from rich import color
from rich import print


def create_dynamic_regex(search_words):
    """
    This function is used to create a dynamic regular expression
    string and a list of random colors. Both these elements will
    be used in the function colorize_text()

    :param search_words: list of search terms
    :return: regular expression search string and a list of colors
    :rtype: string, list
    """
    colors_required = create_list_of_colors(len(search_words))
    number_of_search_words = len(search_words)
    combined_string = ''
    for search_word in search_words:
        number_of_search_words -= 1
        if number_of_search_words != 0:
            current_string = ''.join(r'(\b' + search_word + r'\b)|')
            combined_string = (combined_string + current_string)
        elif number_of_search_words == 0:
            current_string = ''.join(r'(\b' + search_word + r'\b)')
            combined_string = (combined_string + current_string)
    return combined_string, colors_required


def random_color():
    """
    This function is used to create a random color using the
    Python package rich.
    :return: color name
    :rtype: string
    """
    selected_color = random.choice(list(color.ANSI_COLOR_NAMES.keys()))
    return selected_color


def create_list_of_colors(number_of_colors):
    """
    This function is used to generate a list of colors,
    which will be used in the function colorize_text()
    :param number_of_colors:
    :return: list of colors
    :rtype: list
    """
    list_of_colors = [random_color() for _ in range(number_of_colors)]
    return list_of_colors


def colorize_text(text, regex_string, array_of_colors):
    """
    This function is used to colorize specific words in a text string.
    :param text: text string potentially containing specific words to colorize.
    :param regex_string: regular expression search string
    :param array_of_colors: list of colors
    :return: colorized text
    :rtype: string
    """
    available_colors = array_of_colors
    word_regex = regex.compile(f"{regex_string}", regex.IGNORECASE)
    i = 0
    output = ""
    for word in word_regex.finditer(text):
        get_color = available_colors[word.lastindex - 1]
        output += "".join([text[i:word.start()],
                           "[%s]" % available_colors[word.lastindex - 1],
                           text[word.start():word.end()], "[/%s]" % available_colors[word.lastindex - 1]])
        i = word.end()
    return ''.join([output, text[word.end():]])


def generate_console_output(text_to_search, words_to_find):
    """
    This function is used generate colorized text that will
    be outputting to the console.

    :param text_to_search: text string potentially containing specific words to colorize.
    :param words_to_find: list of search terms.
    :return: A string containing colorized words.
    :rtype: string
    """
    search_terms, colors = create_dynamic_regex(words_to_find)
    colorize_html = colorize_text(text_to_search, search_terms, colors)
    print(colorize_html)


text = "The dog chased the cat that was looking for the mouse that the dog was playing with."
words = ['dog', 'cat', 'mouse']
generate_console_output(text, words)

以下是上述代码的打印输出:

我创建了两个用于为文本着色的GIST。

彩色文本终端输出彩色文本HTML输出

一些解决方案包括:

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