如何在Python中将彩色文本输出到终端?
当前回答
我最喜欢的方式是使用祝福库(完整披露:我写的)。例如:
from blessings import Terminal
t = Terminal()
print t.red('This is red.')
print t.bold_bright_red_on_black('Bright red on black')
要打印彩色砖,最可靠的方法是使用背景色打印空间。我使用此技术绘制鼻子进度条:
print t.on_green(' ')
您还可以在特定位置打印:
with t.location(0, 5):
print t.on_yellow(' ')
如果你必须在游戏过程中使用其他终端功能,你也可以这样做。您可以使用Python的标准字符串格式来保持其可读性:
print '{t.clear_eol}You just cleared a {t.bold}whole{t.normal} line!'.format(t=t)
Blessings的优点在于它能在各种终端上工作,而不仅仅是ANSI颜色的终端。它还将不可读的转义序列排除在代码之外,同时保持使用简洁。玩得高兴
其他回答
我的两分钱(PyColorTerm):
安装:
sudo apt-get install python-pip
pip install pycolorterm
Python脚本:
from pycolorterm import pycolorterm
with pycolorterm.pretty_output(pycolorterm.FG_GREEN) as out:
out.write('Works OK!')
“工作正常!”显示为绿色。
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
在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)
我建议这个新图书馆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")
对于Windows,除非使用Win32 API,否则无法使用颜色打印到控制台。
对于Linux,它就像使用打印一样简单,转义序列如下:
颜色
要使字符像方框一样打印,这实际上取决于控制台窗口使用的字体。磅符号效果很好,但它取决于字体:
#