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


当前回答

注意with关键字与需要重置的修饰符(使用Python 3和Colorama)的混合程度:

from colorama import Fore, Style
import sys

class Highlight:
  def __init__(self, clazz, color):
    self.color = color
    self.clazz = clazz
  def __enter__(self):
    print(self.color, end="")
  def __exit__(self, type, value, traceback):
    if self.clazz == Fore:
      print(Fore.RESET, end="")
    else:
      assert self.clazz == Style
      print(Style.RESET_ALL, end="")
    sys.stdout.flush()

with Highlight(Fore, Fore.GREEN):
  print("this is highlighted")
print("this is not")

其他回答

import click

click.secho('Hello, World!', fg='green')
click.secho('Some more text', bg='blue', fg='white')
click.secho('ATTENTION', blink=True, bold=True)

click(CLI库)有一种非常方便的方式来实现这一点,如果您正在编写命令行工具,无论如何都值得考虑。

您想了解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")

对于字符

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

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

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.