如何在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}!")
屏幕截图示例:
其他回答
注意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")
下面是一个可以这样使用的实现:
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()
您可以使用任何语言提供的shell转义字符。这些转义字符以ESC字符开头,后跟一些参数。
例如,要在终端中输出红色“Hello,World!”字符串:
echo "\e[31m Hello, World! \e[0m"
或者从Python脚本:
print("\e[31m Hello world \e[0m")
此外,我写了一篇关于Escape序列的文章,这可能会帮助您更好地理解这个机制。
作为RGB标准的粉丝,我会这样做:
def color_text(text, rgb):
r, g, b = rgb
return f"\033[38;2;{r};{g};{b}m{text}\033[0m"
class rgb():
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
YELLOW = (255, 255, 0)
# and so on ...
print(color_text("hello colored world", rgb.GREEN))
PS:受到CircuitSacul回答的强烈启发
根据乔尔德的回答,这简直太简单了:
class PrintInColor:
RED = '\033[91m'
GREEN = '\033[92m'
YELLOW = '\033[93m'
LIGHT_PURPLE = '\033[94m'
PURPLE = '\033[95m'
END = '\033[0m'
@classmethod
def red(cls, s, **kwargs):
print(cls.RED + s + cls.END, **kwargs)
@classmethod
def green(cls, s, **kwargs):
print(cls.GREEN + s + cls.END, **kwargs)
@classmethod
def yellow(cls, s, **kwargs):
print(cls.YELLOW + s + cls.END, **kwargs)
@classmethod
def lightPurple(cls, s, **kwargs):
print(cls.LIGHT_PURPLE + s + cls.END, **kwargs)
@classmethod
def purple(cls, s, **kwargs):
print(cls.PURPLE + s + cls.END, **kwargs)
那么就
PrintInColor.red('hello', end=' ')
PrintInColor.green('world')