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


当前回答

试试这个简单的代码

def prRed(prt):
    print(f"\033[91m{prt}\033[00m")

def prGreen(prt):
    print(f"\033[92m{prt}\033[00m")

def prYellow(prt):
    print(f"\033[93m{prt}\033[00m")

def prLightPurple(prt):
    print(f"\033[94m{prt}\033[00m")

def prPurple(prt):
    print(f"\033[95m{prt}\033[00m")

def prCyan(prt):
    print(f"\033[96m{prt}\033[00m")

def prLightGray(prt):
    print(f"\033[97m{prt}\033[00m")

def prBlack(prt):
    print(f"\033[98m{prt}\033[00m")

def prReset(prt):
    print(f"\033[0m{prt}\033[00m")

prGreen("Hello, Green World!")
prBlack("Hello, Black World!")
prCyan("Hello, Cyan World!")
prGreen("Hello, Green World!")
prLightGray("Hello, Light Grey World!")
prLightPurple("Hello, Light Purple World!")
prPurple("Hello, Purple World!")
prRed("Hello, Red World!")
prYellow("Hello, Yellow World!")
prReset("Hello, Reset World!")

Python 3示例

# python2
    def prRed(prt): print("\033[91m {}\033[00m" .format(prt))
    def prGreen(prt): print("\033[92m {}\033[00m" .format(prt))
    def prYellow(prt): print("\033[93m {}\033[00m" .format(prt))
    def prLightPurple(prt): print("\033[94m {}\033[00m" .format(prt))
    def prPurple(prt): print("\033[95m {}\033[00m" .format(prt))
    def prCyan(prt): print("\033[96m {}\033[00m" .format(prt))
    def prLightGray(prt): print("\033[97m {}\033[00m" .format(prt))
    def prBlack(prt): print("\033[98m {}\033[00m" .format(prt))

    prGreen("Hello, World!")

其他回答

在Windows上,您可以使用模块“win32console”(在某些Python发行版中可用)或模块“ctypes”(Python 2.5及更高版本)访问Win32 API。

要查看支持这两种方式的完整代码,请参阅Testoob中的彩色控制台报告代码。

ctypes示例:

import ctypes

# Constants from the Windows API
STD_OUTPUT_HANDLE = -11
FOREGROUND_RED    = 0x0004 # text color contains red.

def get_csbi_attributes(handle):
    # Based on IPython's winconsole.py, written by Alexander Belchenko
    import struct
    csbi = ctypes.create_string_buffer(22)
    res = ctypes.windll.kernel32.GetConsoleScreenBufferInfo(handle, csbi)
    assert res

    (bufx, bufy, curx, cury, wattr,
    left, top, right, bottom, maxx, maxy) = struct.unpack("hhhhHhhhhhh", csbi.raw)
    return wattr


handle = ctypes.windll.kernel32.GetStdHandle(STD_OUTPUT_HANDLE)
reset = get_csbi_attributes(handle)

ctypes.windll.kernel32.SetConsoleTextAttribute(handle, FOREGROUND_RED)
print "Cherry on top"
ctypes.windll.kernel32.SetConsoleTextAttribute(handle, reset)

我能找到的最简单的方法不是使用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.")

我建议这个新图书馆Printy。他们刚刚发布了版本1.2.0作为跨平台库。

过来看:GitHub上的Printy

它基于标志,所以你可以做类似的事情

from printy import printy

# With global flags, this will apply a bold (B) red (r) color and an underline (U) to the whole text
printy("Hello, World!", "rBU")

# With inline formats, this will apply a dim (D)
#blue (b) to the word 'Hello' and a stroken (S)
#yellow (y) to the word 'world', and the rest will remain as the predefined format
printy("this is a [bD]Hello@ [yS]world@ text")

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

在我看来,这是最简单的方法。只要您具有所需颜色的RGB值,这应该可以工作:

def colored(r, g, b, text):
    return f"\033[38;2;{r};{g};{b}m{text}\033[0m"

打印红色文本的示例:

text = 'Hello, World!'
colored_text = colored(255, 0, 0, text)
print(colored_text)

#or

print(colored(255, 0, 0, 'Hello, World!'))

多色文本

text = colored(255, 0, 0, 'Hello, ') + colored(0, 255, 0, 'World')
print(text)