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


当前回答

下面是一个可以这样使用的实现:

from stryle import Stryle

print(Stryle.okgreen.bold@"Hello World" + Stryle.underline@'!' + ' back to normal')
print(f"{Stryle.red}Merry {Stryle.underline.okgreen}Christmas!{Stryle.off}")
print("Merry "@Stryle.red + "Christmas"@Stryle.okgreen.underline)

_decorations = {
    "header" : '\033[95m',
    "okblue" : '\033[94m',
    "okcyan" : '\033[96m',
    "okgreen" : '\033[92m',
    "yellow" : '\033[93m',
    "red" : '\033[91m',
    "warning" : '\033[93m',
    "fail" : '\033[91m',
    "off" : '\033[0m',
    "bold" : '\033[1m',
    "underline" : '\033[4m',
}

class _StringStyle(str):
  def __getattribute__(self, decoration: str = _decorations["off"]):
    if decoration in _decorations:
      return _StringStyle(self.decorations + _decorations[decoration])
    return self
  def __matmul__(self, other):
    return self.decorations + str(other) + _decorations["off"]
  def __rmatmul__(self, other):
    return self.decorations + str(other) + _decorations["off"]
  def __str__(self):
    return self.decorations

Stryle = _StringStyle()

其他回答

我编写了一个在PyPI上可用的库,它有一个遵循标准打印函数的简单API。

你可以用pip安装着色来安装它。

import coloring

# Directly use print-like functions
coloring.print_red('Hello', 12)
coloring.print_green('Hey', end="", sep=";")
print()

# Get str as return
print(coloring.red('hello'))

# Use the generic colorize function
print(coloring.colorize("I'm red", "red")) # Using color names
print(coloring.colorize("I'm green", (0, 255, 0)))  # Using RGB colors
print(coloring.colorize("I'm blue", "#0000ff"))  # Using hex colors

# Or using styles (underline, bold, italic, ...)
print(coloring.colorize('Hello', 'red', s='ub'))  # underline and bold

执行代码:

您可以在此处查看所有功能:https://github.com/Nazime/coloring.

一些解决方案包括:

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

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