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


当前回答

最低等级:

class log:
    f = lambda color: lambda string: print(color + string + "\33[0m")

    black = f("\33[30m")
    red = f("\33[31m")
    green = f("\33[32m")
    yellow = f("\33[33m")
    blue = f("\33[34m")
    magenta = f("\33[35m")
    cyan = f("\33[36m")
    white = f("\33[37m")

# Usage
log.blue("Blue World!")

其他回答

asciimatics为构建文本UI和动画提供了可移植的支持:

#!/usr/bin/env python
from asciimatics.effects import RandomNoise  # $ pip install asciimatics
from asciimatics.renderers import SpeechBubble, Rainbow
from asciimatics.scene import Scene
from asciimatics.screen import Screen
from asciimatics.exceptions import ResizeScreenError


def demo(screen):
    render = Rainbow(screen, SpeechBubble('Rainbow'))
    effects = [RandomNoise(screen, signal=render)]
    screen.play([Scene(effects, -1)], stop_on_resize=True)

while True:
    try:
        Screen.wrapper(demo)
        break
    except ResizeScreenError:
        pass

Asciicast:

Rich是一个相对较新的Python库,用于在终端中处理颜色。

在Rich中有几种处理颜色的方法。最快的入门方法是富打印方法,它将类似BBCode的语法呈现到ANSI控制代码中:

from rich import print
print("[red]Color[/] in the [bold magenta]Terminal[/]!")

还有其他方法可以通过Rich(正则表达式、语法)和相关的格式化功能应用颜色。

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

我创建了一个项目(控制台颜色),并已将其发布到PyPI。

你可以抛出pip安装控制台颜色来安装它。

我用斯芬克斯写了文档,读了文档,看这里。

你可以从Googlecolab获得更多的例子。

我仍然发布了一些示例来吸引用户点击上面的链接:

# cprint is something like below
# cprint(text: str, fore: T_RGB = None, bg: T_RGB = None, style: Style = '')
# where T_RGB = Union[Tuple[int, int, int], str] for example. You can input (255, 0, 0) or '#ff0000' or 'ff0000'. They are OK.
# The Style you can input the ``Style.`` (the IDE will help you to choose what you wanted)

# from console_color import RGB, Fore, Style, cprint, create_print
from console_color import *

cprint("Hello, World!", RGB.RED, RGB.YELLOW, Style.BOLD+Style.URL+Style.STRIKE)
cprint("Hello, World!", fore=(255, 0, 0), bg="ffff00", style=Style.BOLD+Style.URL+Style.STRIKE)

当然,您不必输入所有参数。您可以只添加所需的属性。


老实说,这个项目并不特别。它只使用f“\033[{target};2;{r};{g};{b}m{text}{style}”其中target是38或48,text是您的输入字符串,style是“\33[0m',“\33[1m'…”\033[9m'。

我只是让它易于使用(至少对我来说)。

我能找到的最简单的方法不是使用ANSI转义码,而是使用导入模块colorama中的Fore。看看下面的代码:

from colorama import Fore, Style

print(Fore.MAGENTA + "IZZ MAGENTA BRUH.")

print(Style.RESET_ALL + "IZZ BACK TO NORMALZ.")

与ANSI转义码相比:

print("\u001b[31m IZZ RED (NO MAGENTA ON ANSI CODES).\u001b[0m")

print("BACK TO NORMALZ.")