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


当前回答

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

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

其他回答

在我看来,这是最简单的方法。只要您具有所需颜色的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)

在Windows上,您可以使用模块“win32console”(在某些Python发行版中可用)或模块“ctypes”(Python 2.5及更高版本)访问Win32 API。

要查看支持这两种方式的完整代码,请参阅Testoob中的彩色控制台报告代码。

ctypes示例:

import ctypes

# Constants from the Windows API
STD_OUTPUT_HANDLE = -11
FOREGROUND_RED    = 0x0004 # text color contains red.

def get_csbi_attributes(handle):
    # Based on IPython's winconsole.py, written by Alexander Belchenko
    import struct
    csbi = ctypes.create_string_buffer(22)
    res = ctypes.windll.kernel32.GetConsoleScreenBufferInfo(handle, csbi)
    assert res

    (bufx, bufy, curx, cury, wattr,
    left, top, right, bottom, maxx, maxy) = struct.unpack("hhhhHhhhhhh", csbi.raw)
    return wattr


handle = ctypes.windll.kernel32.GetStdHandle(STD_OUTPUT_HANDLE)
reset = get_csbi_attributes(handle)

ctypes.windll.kernel32.SetConsoleTextAttribute(handle, FOREGROUND_RED)
print "Cherry on top"
ctypes.windll.kernel32.SetConsoleTextAttribute(handle, reset)
class ColorText:
    """
    Use ANSI escape sequences to print colors +/- bold/underline to bash terminal.

    Examples
    --------
    >>> ColorText('HelloWorld').bold()
    >>> ColorText('HelloWorld').blue()
    >>> ColorText('HelloWorld').bold().custom("#bebebe")
    >>> ColorText('HelloWorld').underline().custom('dodgerblue')
    >>> ColorText.demo()

    Notes
    -----
    - execute ColorText.demo() for a printout of colors.
    """

    @classmethod
    def demo(cls):
        """Prints examples of all colors in normal, bold, underline, bold+underline."""
        for color in dir(ColorText):
            if all([color.startswith("_") is False,
                    color not in ["bold", "underline", "demo", "custom"],
                    callable(getattr(ColorText, color))]):
                print(getattr(ColorText(color), color)(),
                      "\t",
                      getattr(ColorText(f"bold {color}").bold(), color)(),
                      "\t",
                      getattr(ColorText(f"underline {color}").underline(), color)(),
                      "\t",
                      getattr(ColorText(f"bold underline {color}").underline().bold(), color)())
        print(ColorText("Input can also be color hex or R,G,B with ColorText.custom()").bold())
        pass

    def __init__(self, text: str = ""):
        self.text = text
        self.ending = "\033[0m"
        self.colors = []
        pass

    def __repr__(self):
        return self.text

    def __str__(self):
        return self.text

    def bold(self):
        self.text = "\033[1m" + self.text + self.ending
        return self

    def underline(self):
        self.text = "\033[4m" + self.text + self.ending
        return self

    def green(self):
        self.text = "\033[92m" + self.text + self.ending
        self.colors.append("green")
        return self

    def purple(self):
        self.text = "\033[95m" + self.text + self.ending
        self.colors.append("purple")
        return self

    def blue(self):
        self.text = "\033[94m" + self.text + self.ending
        self.colors.append("blue")
        return self

    def ltblue(self):
        self.text = "\033[34m" + self.text + self.ending
        self.colors.append("lightblue")
        return self

    def pink(self):
        self.text = "\033[35m" + self.text + self.ending
        self.colors.append("pink")
        return self

    def gray(self):
        self.text = "\033[30m" + self.text + self.ending
        self.colors.append("gray")
        return self

    def ltgray(self):
        self.text = "\033[37m" + self.text + self.ending
        self.colors.append("ltgray")
        return self

    def warn(self):
        self.text = "\033[93m" + self.text + self.ending
        self.colors.append("yellow")
        return self

    def fail(self):
        self.text = "\033[91m" + self.text + self.ending
        self.colors.append("red")
        return self

    def ltred(self):
        self.text = "\033[31m" + self.text + self.ending
        self.colors.append("lightred")
        return self

    def cyan(self):
        self.text = "\033[36m" + self.text + self.ending
        self.colors.append("cyan")
        return self

    def custom(self, *color_hex):
        """Print in custom color, `color_hex` - either actual hex, or tuple(r,g,b)"""
        if color_hex != (None, ):  # allows printing white on black background, black otherwise
            if len(color_hex) == 1:
                c = rgb2hex(colorConverter.to_rgb(color_hex[0]))
                rgb = ImageColor.getcolor(c, "RGB")
            else:
                assert (
                    len(color_hex) == 3
                ), "If not a color hex, ColorText.custom should have R,G,B as input"
                rgb = color_hex
            self.text = "\033[{};2;{};{};{}m".format(38, *rgb) + self.text + self.ending
            self.colors.append(rgb)
        return self

    pass

对于字符

您的终端很可能使用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是您要使用的模块。查看本教程。

我编写了一个在Linux、OS X和Windows中处理颜色的模块。它支持所有平台上的所有16种颜色,您可以在不同的时间设置前景和背景颜色,字符串对象可以为len()和.capitalize()等对象提供正常的结果。

https://github.com/Robpol86/colorclass