如何在Python中将彩色文本输出到终端?
当前回答
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
其他回答
试试这个简单的代码
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!")
如果你正在编程一个游戏,也许你想改变背景颜色,只使用空格?例如:
print " "+ "\033[01;41m" + " " +"\033[01;46m" + " " + "\033[01;42m"
我建议这个新图书馆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")
这里有一个快速类,它包装了一个打印功能,可以快速添加颜色,而无需安装其他软件包。
class PrintColored:
DEFAULT = '\033[0m'
# Styles
BOLD = '\033[1m'
ITALIC = '\033[3m'
UNDERLINE = '\033[4m'
UNDERLINE_THICK = '\033[21m'
HIGHLIGHTED = '\033[7m'
HIGHLIGHTED_BLACK = '\033[40m'
HIGHLIGHTED_RED = '\033[41m'
HIGHLIGHTED_GREEN = '\033[42m'
HIGHLIGHTED_YELLOW = '\033[43m'
HIGHLIGHTED_BLUE = '\033[44m'
HIGHLIGHTED_PURPLE = '\033[45m'
HIGHLIGHTED_CYAN = '\033[46m'
HIGHLIGHTED_GREY = '\033[47m'
HIGHLIGHTED_GREY_LIGHT = '\033[100m'
HIGHLIGHTED_RED_LIGHT = '\033[101m'
HIGHLIGHTED_GREEN_LIGHT = '\033[102m'
HIGHLIGHTED_YELLOW_LIGHT = '\033[103m'
HIGHLIGHTED_BLUE_LIGHT = '\033[104m'
HIGHLIGHTED_PURPLE_LIGHT = '\033[105m'
HIGHLIGHTED_CYAN_LIGHT = '\033[106m'
HIGHLIGHTED_WHITE_LIGHT = '\033[107m'
STRIKE_THROUGH = '\033[9m'
MARGIN_1 = '\033[51m'
MARGIN_2 = '\033[52m' # seems equal to MARGIN_1
# colors
BLACK = '\033[30m'
RED_DARK = '\033[31m'
GREEN_DARK = '\033[32m'
YELLOW_DARK = '\033[33m'
BLUE_DARK = '\033[34m'
PURPLE_DARK = '\033[35m'
CYAN_DARK = '\033[36m'
GREY_DARK = '\033[37m'
BLACK_LIGHT = '\033[90m'
RED = '\033[91m'
GREEN = '\033[92m'
YELLOW = '\033[93m'
BLUE = '\033[94m'
PURPLE = '\033[95m'
CYAN = '\033[96m'
WHITE = '\033[96m'
def __init__(self):
self.print_original = print # old value to the original print function
self.current_color = self.DEFAULT
def __call__(self,
*values: object, sep: str | None = None,
end: str | None = None,
file: str | None = None,
flush: bool = False,
color: str|None = None,
default_color: str|None = None,
):
if default_color:
self.current_color = default_color
default = self.current_color
if color:
values = (color, *values, default) # wrap the content within a selected color an a default
else:
values = (*values, default) # wrap the content within a selected color an a default
self.print_original(*values, end=end, file=file, flush=flush)
用法
class PrintColored:
DEFAULT = '\033[0m'
# Styles
BOLD = '\033[1m'
ITALIC = '\033[3m'
UNDERLINE = '\033[4m'
UNDERLINE_THICK = '\033[21m'
HIGHLIGHTED = '\033[7m'
HIGHLIGHTED_BLACK = '\033[40m'
HIGHLIGHTED_RED = '\033[41m'
HIGHLIGHTED_GREEN = '\033[42m'
HIGHLIGHTED_YELLOW = '\033[43m'
HIGHLIGHTED_BLUE = '\033[44m'
HIGHLIGHTED_PURPLE = '\033[45m'
HIGHLIGHTED_CYAN = '\033[46m'
HIGHLIGHTED_GREY = '\033[47m'
HIGHLIGHTED_GREY_LIGHT = '\033[100m'
HIGHLIGHTED_RED_LIGHT = '\033[101m'
HIGHLIGHTED_GREEN_LIGHT = '\033[102m'
HIGHLIGHTED_YELLOW_LIGHT = '\033[103m'
HIGHLIGHTED_BLUE_LIGHT = '\033[104m'
HIGHLIGHTED_PURPLE_LIGHT = '\033[105m'
HIGHLIGHTED_CYAN_LIGHT = '\033[106m'
HIGHLIGHTED_WHITE_LIGHT = '\033[107m'
STRIKE_THROUGH = '\033[9m'
MARGIN_1 = '\033[51m'
MARGIN_2 = '\033[52m' # seems equal to MARGIN_1
# colors
BLACK = '\033[30m'
RED_DARK = '\033[31m'
GREEN_DARK = '\033[32m'
YELLOW_DARK = '\033[33m'
BLUE_DARK = '\033[34m'
PURPLE_DARK = '\033[35m'
CYAN_DARK = '\033[36m'
GREY_DARK = '\033[37m'
BLACK_LIGHT = '\033[90m'
RED = '\033[91m'
GREEN = '\033[92m'
YELLOW = '\033[93m'
BLUE = '\033[94m'
PURPLE = '\033[95m'
CYAN = '\033[96m'
WHITE = '\033[96m'
def __init__(self):
self.print_original = print # old value to the original print function
self.current_color = self.DEFAULT
def __call__(self,
*values: object, sep: str | None = None,
end: str | None = None,
file: str | None = None,
flush: bool = False,
color: str|None = None,
default_color: str|None = None,
):
if default_color:
self.current_color = default_color
default = self.current_color
if color:
values = (color, *values, default) # wrap the content within a selected color an a default
else:
values = (*values, default) # wrap the content within a selected color an a default
self.print_original(*values, end=end, file=file, flush=flush)
if __name__ == '__main__':
print = PrintColored()
print("Hello world - default")
print("Hello world - Bold", color=print.BOLD)
print("Hello world - Italic", color=print.ITALIC)
print("Hello world - Underline", color=print.UNDERLINE)
print("Hello world - UNDERLINE_THICK", color=print.UNDERLINE_THICK)
print("Hello world - HighLithted", color=print.HIGHLIGHTED)
print("Hello world - HIGHLIGHTED_BLACK", color=print.HIGHLIGHTED_BLACK)
print("Hello world - HIGHLIGHTED_RED", color=print.HIGHLIGHTED_RED)
print("Hello world - HIGHLIGHTED_GREEN", color=print.HIGHLIGHTED_GREEN)
print("Hello world - HIGHLIGHTED_YELLOW", color=print.HIGHLIGHTED_YELLOW)
print("Hello world - HIGHLIGHTED_BLUE", color=print.HIGHLIGHTED_BLUE)
print("Hello world - HIGHLIGHTED_PURPLE", color=print.HIGHLIGHTED_PURPLE)
print("Hello world - HIGHLIGHTED_CYAN", color=print.HIGHLIGHTED_CYAN)
print("Hello world - HIGHLIGHTED_GREY", color=print.HIGHLIGHTED_GREY)
print("Hello world - HIGHLIGHTED_GREY_LIGHT", color=print.HIGHLIGHTED_GREY_LIGHT)
print("Hello world - HIGHLIGHTED_RED_LIGHT", color=print.HIGHLIGHTED_RED_LIGHT)
print("Hello world - HIGHLIGHTED_GREEN_LIGHT", color=print.HIGHLIGHTED_GREEN_LIGHT)
print("Hello world - HIGHLIGHTED_YELLOW_LIGHT", color=print.HIGHLIGHTED_YELLOW_LIGHT)
print("Hello world - HIGHLIGHTED_BLUE_LIGHT", color=print.HIGHLIGHTED_BLUE_LIGHT)
print("Hello world - HIGHLIGHTED_PURPLE_LIGHT", color=print.HIGHLIGHTED_PURPLE_LIGHT)
print("Hello world - HIGHLIGHTED_CYAN_LIGHT", color=print.HIGHLIGHTED_CYAN_LIGHT)
print("Hello world - HIGHLIGHTED_WHITE_LIGHT", color=print.HIGHLIGHTED_WHITE_LIGHT)
print("Hello world - STRIKE_THROUGH", color=print.STRIKE_THROUGH)
print("Hello world - MARGIN_1", color=print.MARGIN_1)
print("Hello world - MARGIN_2", color=print.MARGIN_2)
print("Hello world - BLACK", color=print.BLACK)
print("Hello world - RED_DARK", color=print.RED_DARK)
print("Hello world - GREEN_DARK", color=print.GREEN_DARK)
print("Hello world - YELLOW_DARK", color=print.YELLOW_DARK)
print("Hello world - BLUE_DARK", color=print.BLUE_DARK)
print("Hello world - PURPLE_DARK", color=print.PURPLE_DARK)
print("Hello world - CYAN_DARK", color=print.CYAN_DARK)
print("Hello world - GREY_DARK", color=print.GREY_DARK)
print("Hello world - BLACK_LIGHT", color=print.BLACK_LIGHT)
print("Hello world - BLACK_LIGHT", color=print.BLACK_LIGHT)
print("Hello world - RED", color=print.RED)
print("Hello world - GREEN", color=print.GREEN)
print("Hello world - YELLOW", color=print.YELLOW)
print("Hello world - BLUE", color=print.BLUE)
print("Hello world - PURPLE", color=print.PURPLE)
print("Hello world - CYAN", color=print.CYAN)
print("Hello world - WHITE", color=print.WHITE)
# Back to normal
print("", default_color=print.DEFAULT)
print("Hello world - default")
输出
这在某种程度上取决于您所在的平台。最常见的方法是打印ANSI转义序列。举个简单的例子,这里有一些来自Blender构建脚本的Python代码:
class bcolors:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKCYAN = '\033[96m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
要使用这样的代码,可以执行以下操作:
print(bcolors.WARNING + "Warning: No active frommets remain. Continue?" + bcolors.ENDC)
或者,使用Python 3.6+:
print(f"{bcolors.WARNING}Warning: No active frommets remain. Continue?{bcolors.ENDC}")
这将在包括OS X、Linux和Windows在内的UNIX上运行(如果您使用ANSICON,或者在Windows 10中启用VT100仿真)。有用于设置颜色、移动光标等的ANSI代码。
如果你要对此感到复杂(如果你正在编写游戏,这听起来就像是这样),你应该看看“诅咒”模块,它为你处理了很多复杂的部分。Python诅咒HowTO是一个很好的介绍。
如果您不使用扩展ASCII(即,不在PC上),则您只能使用127以下的ASCII字符,而“#”或“@”可能是块的最佳选择。如果您可以确保您的终端使用的是IBM扩展的ASCII字符集,那么您有更多的选项。字符176、177、178和219是“块字符”。
一些基于文本的现代程序,如“矮人堡垒”,以图形模式模拟文本模式,并使用经典PC字体的图像。您可以在矮人要塞Wiki中找到一些位图(用户制作的瓷砖)。
文本模式演示比赛有更多的资源用于在文本模式下制作图形。
推荐文章
- 将Pandas或Numpy Nan替换为None以用于MysqlDB
- 使用pandas对同一列进行多个聚合
- 使用Python解析HTML
- django MultiValueDictKeyError错误,我如何处理它
- 如何在for循环期间修改列表条目?
- 我如何在Django中创建一个鼻涕虫?
- 没有名为'django.core.urlresolvers'的模块
- 蟒蛇导出环境文件
- Django - makemigrations -未检测到任何更改
- SQLAlchemy:引擎、连接和会话差异
- 在Python Pandas中删除多个列中的所有重复行
- 更改pandas DataFrame中的特定列名
- 将Pandas多索引转换为列
- 熊猫在每组中获得最高的n个记录
- 熊猫数据帧得到每组的第一行