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


当前回答

我的两分钱(PyColorTerm):

安装:

sudo apt-get install python-pip
pip install pycolorterm

Python脚本:

from pycolorterm import pycolorterm

with pycolorterm.pretty_output(pycolorterm.FG_GREEN) as out:
    out.write('Works OK!')

“工作正常!”显示为绿色。

其他回答

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

这个答案还使用了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输出

另一个包装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'])

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

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')

在我看来,这是最简单的方法。只要您具有所需颜色的RGB值,这应该可以工作:

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

打印红色文本的示例:

text = 'Hello, World!'
colored_text = colored(255, 0, 0, text)
print(colored_text)

#or

print(colored(255, 0, 0, 'Hello, World!'))

多色文本

text = colored(255, 0, 0, 'Hello, ') + colored(0, 255, 0, 'World')
print(text)

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

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

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

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

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

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

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

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

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

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

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

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

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