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


当前回答

https://raw.github.com/fabric/fabric/master/fabric/colors.py

"""
.. versionadded:: 0.9.2

Functions for wrapping strings in ANSI color codes.

Each function within this module returns the input string ``text``, wrapped
with ANSI color codes for the appropriate color.

For example, to print some text as green on supporting terminals::

    from fabric.colors import green

    print(green("This text is green!"))

Because these functions simply return modified strings, you can nest them::

    from fabric.colors import red, green

    print(red("This sentence is red, except for " + \
          green("these words, which are green") + "."))

If ``bold`` is set to ``True``, the ANSI flag for bolding will be flipped on
for that particular invocation, which usually shows up as a bold or brighter
version of the original color on most terminals.
"""


def _wrap_with(code):

    def inner(text, bold=False):
        c = code
        if bold:
            c = "1;%s" % c
        return "\033[%sm%s\033[0m" % (c, text)
    return inner

red = _wrap_with('31')
green = _wrap_with('32')
yellow = _wrap_with('33')
blue = _wrap_with('34')
magenta = _wrap_with('35')
cyan = _wrap_with('36')
white = _wrap_with('37')

其他回答

您可以使用任何语言提供的shell转义字符。这些转义字符以ESC字符开头,后跟一些参数。

例如,要在终端中输出红色“Hello,World!”字符串:

echo "\e[31m Hello, World! \e[0m"

或者从Python脚本:

print("\e[31m Hello world \e[0m")

此外,我写了一篇关于Escape序列的文章,这可能会帮助您更好地理解这个机制。

考虑到您是否正在编写命令行工具,这是最简单和方便的方法。这种方法可以在所有控制台上的任何地方工作,而无需安装任何花哨的软件包。

要使ANSI代码在Windows上运行,首先,运行os.system('color')

import os
os.system('color')

COLOR = '\033[91m'  # change it, according to the color need

END = '\033[0m'

print(COLOR + "Hello World" + END) #print a message


exit=input() #to avoid closing the terminal windows


更多颜色:

注意:\33[5m和\33[6m闪烁。

感谢@qubodup

注意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")

这在某种程度上取决于您所在的平台。最常见的方法是打印ANSI转义序列。举个简单的例子,这里有一些来自Blender构建脚本的Python代码:

class bcolors:
    HEADER = '\033[95m'
    OKBLUE = '\033[94m'
    OKCYAN = '\033[96m'
    OKGREEN = '\033[92m'
    WARNING = '\033[93m'
    FAIL = '\033[91m'
    ENDC = '\033[0m'
    BOLD = '\033[1m'
    UNDERLINE = '\033[4m'

要使用这样的代码,可以执行以下操作:

print(bcolors.WARNING + "Warning: No active frommets remain. Continue?" + bcolors.ENDC)

或者,使用Python 3.6+:

print(f"{bcolors.WARNING}Warning: No active frommets remain. Continue?{bcolors.ENDC}")

这将在包括OS X、Linux和Windows在内的UNIX上运行(如果您使用ANSICON,或者在Windows 10中启用VT100仿真)。有用于设置颜色、移动光标等的ANSI代码。

如果你要对此感到复杂(如果你正在编写游戏,这听起来就像是这样),你应该看看“诅咒”模块,它为你处理了很多复杂的部分。Python诅咒HowTO是一个很好的介绍。

如果您不使用扩展ASCII(即,不在PC上),则您只能使用127以下的ASCII字符,而“#”或“@”可能是块的最佳选择。如果您可以确保您的终端使用的是IBM扩展的ASCII字符集,那么您有更多的选项。字符176、177、178和219是“块字符”。

一些基于文本的现代程序,如“矮人堡垒”,以图形模式模拟文本模式,并使用经典PC字体的图像。您可以在矮人要塞Wiki中找到一些位图(用户制作的瓷砖)。

文本模式演示比赛有更多的资源用于在文本模式下制作图形。

我编写了一个简单的模块,可在以下网址获得:http://pypi.python.org/pypi/colorconsole

它适用于Windows、Mac OS X和Linux。它在Linux和Mac上使用ANSI,但在Windows上使用对控制台函数的本地调用。你有颜色、光标定位和键盘输入。它不是诅咒的替代品,但如果您需要在简单脚本或ASCII游戏中使用,它可能非常有用。