如何在Python中将彩色文本输出到终端?
当前回答
还有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')
其他回答
class ColorText:
"""
Use ANSI escape sequences to print colors +/- bold/underline to bash terminal.
Examples
--------
>>> ColorText('HelloWorld').bold()
>>> ColorText('HelloWorld').blue()
>>> ColorText('HelloWorld').bold().custom("#bebebe")
>>> ColorText('HelloWorld').underline().custom('dodgerblue')
>>> ColorText.demo()
Notes
-----
- execute ColorText.demo() for a printout of colors.
"""
@classmethod
def demo(cls):
"""Prints examples of all colors in normal, bold, underline, bold+underline."""
for color in dir(ColorText):
if all([color.startswith("_") is False,
color not in ["bold", "underline", "demo", "custom"],
callable(getattr(ColorText, color))]):
print(getattr(ColorText(color), color)(),
"\t",
getattr(ColorText(f"bold {color}").bold(), color)(),
"\t",
getattr(ColorText(f"underline {color}").underline(), color)(),
"\t",
getattr(ColorText(f"bold underline {color}").underline().bold(), color)())
print(ColorText("Input can also be color hex or R,G,B with ColorText.custom()").bold())
pass
def __init__(self, text: str = ""):
self.text = text
self.ending = "\033[0m"
self.colors = []
pass
def __repr__(self):
return self.text
def __str__(self):
return self.text
def bold(self):
self.text = "\033[1m" + self.text + self.ending
return self
def underline(self):
self.text = "\033[4m" + self.text + self.ending
return self
def green(self):
self.text = "\033[92m" + self.text + self.ending
self.colors.append("green")
return self
def purple(self):
self.text = "\033[95m" + self.text + self.ending
self.colors.append("purple")
return self
def blue(self):
self.text = "\033[94m" + self.text + self.ending
self.colors.append("blue")
return self
def ltblue(self):
self.text = "\033[34m" + self.text + self.ending
self.colors.append("lightblue")
return self
def pink(self):
self.text = "\033[35m" + self.text + self.ending
self.colors.append("pink")
return self
def gray(self):
self.text = "\033[30m" + self.text + self.ending
self.colors.append("gray")
return self
def ltgray(self):
self.text = "\033[37m" + self.text + self.ending
self.colors.append("ltgray")
return self
def warn(self):
self.text = "\033[93m" + self.text + self.ending
self.colors.append("yellow")
return self
def fail(self):
self.text = "\033[91m" + self.text + self.ending
self.colors.append("red")
return self
def ltred(self):
self.text = "\033[31m" + self.text + self.ending
self.colors.append("lightred")
return self
def cyan(self):
self.text = "\033[36m" + self.text + self.ending
self.colors.append("cyan")
return self
def custom(self, *color_hex):
"""Print in custom color, `color_hex` - either actual hex, or tuple(r,g,b)"""
if color_hex != (None, ): # allows printing white on black background, black otherwise
if len(color_hex) == 1:
c = rgb2hex(colorConverter.to_rgb(color_hex[0]))
rgb = ImageColor.getcolor(c, "RGB")
else:
assert (
len(color_hex) == 3
), "If not a color hex, ColorText.custom should have R,G,B as input"
rgb = color_hex
self.text = "\033[{};2;{};{};{}m".format(38, *rgb) + self.text + self.ending
self.colors.append(rgb)
return self
pass
您可以使用Clint:
from clint.textui import colored
print colored.red('some warning message')
print colored.green('nicely done!')
对于Windows,除非使用Win32 API,否则无法使用颜色打印到控制台。
对于Linux,它就像使用打印一样简单,转义序列如下:
颜色
要使字符像方框一样打印,这实际上取决于控制台窗口使用的字体。磅符号效果很好,但它取决于字体:
#
我编写了一个在Linux、OS X和Windows中处理颜色的模块。它支持所有平台上的所有16种颜色,您可以在不同的时间设置前景和背景颜色,字符串对象可以为len()和.capitalize()等对象提供正常的结果。
https://github.com/Robpol86/colorclass
一些解决方案包括:
fg = lambda text, color: "\33[38;5;" + str(color) + "m" + text + "\33[0m"
bg = lambda text, color: "\33[48;5;" + str(color) + "m" + text + "\33[0m"
def print_six(row, format, end="\n"):
for col in range(6):
color = row*6 + col - 2
if color>=0:
text = "{:3d}".format(color)
print (format(text,color), end=" ")
else:
print(end=" ") # Four spaces
print(end=end)
for row in range(0, 43):
print_six(row, fg, " ")
print_six(row, bg)
print(fg("text", 160))
OR
def colored(r, g, b, text):
return "\033[38;2;{};{};{}m{} \033[38;2;255;255;255m".format(r, g, b, text)
text = 'Hello, World!'
colored_text = colored(255, 0, 0, text)
print(colored_text)
OR
class Color:
COLOR = [f"\33[{i}m" for i in range(44)]
for i in range(44):
print(Color.COLOR[i] + 'text')
可能无法在Windows 10终端或PowerShell窗口上运行,或者在其他情况下可能无法直接运行。
但在插入时,程序开头的这两行可能会有所帮助:
import os
os.system('')
os.system(“”)允许您在终端中打印ANSI代码,根据您的选择对输出进行着色(但可能需要调用其他特定于系统的函数,以便能够在终端中显示彩色文本)。