如何在Python中将彩色文本输出到终端?
当前回答
答案是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}!")
屏幕截图示例:
其他回答
在我看来,这是最简单的方法。只要您具有所需颜色的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)
还有Python termcolor模块。用法很简单:
from termcolor import colored
print colored('hello', 'red'), colored('world', 'green')
或者在Python 3中:
print(colored('hello', 'red'), colored('world', 'green'))
然而,对于游戏编程和你想做的“彩色方块”来说,它可能不够复杂。。。
要使ANSI代码在windows上运行,请首先运行
os.system('color')
注意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")
您可以使用Clint:
from clint.textui import colored
print colored.red('some warning message')
print colored.green('nicely done!')
def black(text):
print('\033[30m', text, '\033[0m', sep='')
def red(text):
print('\033[31m', text, '\033[0m', sep='')
def green(text):
print('\033[32m', text, '\033[0m', sep='')
def yellow(text):
print('\033[33m', text, '\033[0m', sep='')
def blue(text):
print('\033[34m', text, '\033[0m', sep='')
def magenta(text):
print('\033[35m', text, '\033[0m', sep='')
def cyan(text):
print('\033[36m', text, '\033[0m', sep='')
def gray(text):
print('\033[90m', text, '\033[0m', sep='')
black("BLACK")
red("RED")
green("GREEN")
yellow("YELLOW")
blue("BLACK")
magenta("MAGENTA")
cyan("CYAN")
gray("GRAY")
联机尝试