如何在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 ... ")

其他回答

您想了解ANSI转义序列。下面是一个简单的例子:

CSI = "\x1B["
print(CSI+"31;40m" + "Colored Text" + CSI + "0m")

有关详细信息,请参见ANSI转义码。

对于块字符,请尝试使用Unicode字符,如\u2588:

print(u"\u2588")

将所有内容放在一起:

print(CSI+"31;40m" + u"\u2588" + CSI + "0m")

如果你正在编程一个游戏,也许你想改变背景颜色,只使用空格?例如:

print " "+ "\033[01;41m" + " " +"\033[01;46m"  + "  " + "\033[01;42m"

下面是一个诅咒示例:

import curses

def main(stdscr):
    stdscr.clear()
    if curses.has_colors():
        for i in xrange(1, curses.COLORS):
            curses.init_pair(i, i, curses.COLOR_BLACK)
            stdscr.addstr("COLOR %d! " % i, curses.color_pair(i))
            stdscr.addstr("BOLD! ", curses.color_pair(i) | curses.A_BOLD)
            stdscr.addstr("STANDOUT! ", curses.color_pair(i) | curses.A_STANDOUT)
            stdscr.addstr("UNDERLINE! ", curses.color_pair(i) | curses.A_UNDERLINE)
            stdscr.addstr("BLINK! ", curses.color_pair(i) | curses.A_BLINK)
            stdscr.addstr("DIM! ", curses.color_pair(i) | curses.A_DIM)
            stdscr.addstr("REVERSE! ", curses.color_pair(i) | curses.A_REVERSE)
    stdscr.refresh()
    stdscr.getch()

if __name__ == '__main__':
    print "init..."
    curses.wrapper(main)

我创建了一个项目(控制台颜色),并已将其发布到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'。

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

答案是Python中所有跨平台着色的Colorama。

它支持Python 3.5+以及Python 2.7。

截至2021 1月,这一数字仍保持不变。

示例代码:

from colorama import init as colorama_init
from colorama import Fore
from colorama import Style

colorama_init()

print(f"This is {Fore.GREEN}color{Style.RESET_ALL}!")

屏幕截图示例: