如何在Python中将彩色文本输出到终端?
当前回答
定义开始颜色的字符串和结束颜色的字符串。然后打印文本,开始字符串在前面,结束字符串在结尾。
CRED = '\033[91m'
CEND = '\033[0m'
print(CRED + "Error, does not compute!" + CEND)
这将在Bash和urxvt中使用Zenburn风格的配色方案生成以下内容:
通过实验,我们可以获得更多的颜色:
注意:\33[5m和\33[6m闪烁。
这样我们可以创建一个完整的颜色集合:
CEND = '\33[0m'
CBOLD = '\33[1m'
CITALIC = '\33[3m'
CURL = '\33[4m'
CBLINK = '\33[5m'
CBLINK2 = '\33[6m'
CSELECTED = '\33[7m'
CBLACK = '\33[30m'
CRED = '\33[31m'
CGREEN = '\33[32m'
CYELLOW = '\33[33m'
CBLUE = '\33[34m'
CVIOLET = '\33[35m'
CBEIGE = '\33[36m'
CWHITE = '\33[37m'
CBLACKBG = '\33[40m'
CREDBG = '\33[41m'
CGREENBG = '\33[42m'
CYELLOWBG = '\33[43m'
CBLUEBG = '\33[44m'
CVIOLETBG = '\33[45m'
CBEIGEBG = '\33[46m'
CWHITEBG = '\33[47m'
CGREY = '\33[90m'
CRED2 = '\33[91m'
CGREEN2 = '\33[92m'
CYELLOW2 = '\33[93m'
CBLUE2 = '\33[94m'
CVIOLET2 = '\33[95m'
CBEIGE2 = '\33[96m'
CWHITE2 = '\33[97m'
CGREYBG = '\33[100m'
CREDBG2 = '\33[101m'
CGREENBG2 = '\33[102m'
CYELLOWBG2 = '\33[103m'
CBLUEBG2 = '\33[104m'
CVIOLETBG2 = '\33[105m'
CBEIGEBG2 = '\33[106m'
CWHITEBG2 = '\33[107m'
以下是生成测试的代码:
x = 0
for i in range(24):
colors = ""
for j in range(5):
code = str(x+j)
colors = colors + "\33[" + code + "m\\33[" + code + "m\033[0m "
print(colors)
x = x + 5
其他回答
我创建了一个项目(控制台颜色),并已将其发布到PyPI。
你可以抛出pip安装控制台颜色来安装它。
我用斯芬克斯写了文档,读了文档,看这里。
你可以从Googlecolab获得更多的例子。
我仍然发布了一些示例来吸引用户点击上面的链接:
# cprint is something like below
# cprint(text: str, fore: T_RGB = None, bg: T_RGB = None, style: Style = '')
# where T_RGB = Union[Tuple[int, int, int], str] for example. You can input (255, 0, 0) or '#ff0000' or 'ff0000'. They are OK.
# The Style you can input the ``Style.`` (the IDE will help you to choose what you wanted)
# from console_color import RGB, Fore, Style, cprint, create_print
from console_color import *
cprint("Hello, World!", RGB.RED, RGB.YELLOW, Style.BOLD+Style.URL+Style.STRIKE)
cprint("Hello, World!", fore=(255, 0, 0), bg="ffff00", style=Style.BOLD+Style.URL+Style.STRIKE)
当然,您不必输入所有参数。您可以只添加所需的属性。
老实说,这个项目并不特别。它只使用f“\033[{target};2;{r};{g};{b}m{text}{style}”其中target是38或48,text是您的输入字符串,style是“\33[0m',“\33[1m'…”\033[9m'。
我只是让它易于使用(至少对我来说)。
这在某种程度上取决于您所在的平台。最常见的方法是打印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中找到一些位图(用户制作的瓷砖)。
文本模式演示比赛有更多的资源用于在文本模式下制作图形。
定义开始颜色的字符串和结束颜色的字符串。然后打印文本,开始字符串在前面,结束字符串在结尾。
CRED = '\033[91m'
CEND = '\033[0m'
print(CRED + "Error, does not compute!" + CEND)
这将在Bash和urxvt中使用Zenburn风格的配色方案生成以下内容:
通过实验,我们可以获得更多的颜色:
注意:\33[5m和\33[6m闪烁。
这样我们可以创建一个完整的颜色集合:
CEND = '\33[0m'
CBOLD = '\33[1m'
CITALIC = '\33[3m'
CURL = '\33[4m'
CBLINK = '\33[5m'
CBLINK2 = '\33[6m'
CSELECTED = '\33[7m'
CBLACK = '\33[30m'
CRED = '\33[31m'
CGREEN = '\33[32m'
CYELLOW = '\33[33m'
CBLUE = '\33[34m'
CVIOLET = '\33[35m'
CBEIGE = '\33[36m'
CWHITE = '\33[37m'
CBLACKBG = '\33[40m'
CREDBG = '\33[41m'
CGREENBG = '\33[42m'
CYELLOWBG = '\33[43m'
CBLUEBG = '\33[44m'
CVIOLETBG = '\33[45m'
CBEIGEBG = '\33[46m'
CWHITEBG = '\33[47m'
CGREY = '\33[90m'
CRED2 = '\33[91m'
CGREEN2 = '\33[92m'
CYELLOW2 = '\33[93m'
CBLUE2 = '\33[94m'
CVIOLET2 = '\33[95m'
CBEIGE2 = '\33[96m'
CWHITE2 = '\33[97m'
CGREYBG = '\33[100m'
CREDBG2 = '\33[101m'
CGREENBG2 = '\33[102m'
CYELLOWBG2 = '\33[103m'
CBLUEBG2 = '\33[104m'
CVIOLETBG2 = '\33[105m'
CBEIGEBG2 = '\33[106m'
CWHITEBG2 = '\33[107m'
以下是生成测试的代码:
x = 0
for i in range(24):
colors = ""
for j in range(5):
code = str(x+j)
colors = colors + "\33[" + code + "m\\33[" + code + "m\033[0m "
print(colors)
x = x + 5
基于joeld的答案,使用https://pypi.python.org/pypi/lazyme 管道安装-U lazyme:
from lazyme.string import color_print
>>> color_print('abc')
abc
>>> color_print('abc', color='pink')
abc
>>> color_print('abc', color='red')
abc
>>> color_print('abc', color='yellow')
abc
>>> color_print('abc', color='green')
abc
>>> color_print('abc', color='blue', underline=True)
abc
>>> color_print('abc', color='blue', underline=True, bold=True)
abc
>>> color_print('abc', color='pink', underline=True, bold=True)
abc
截图:
使用新的格式化程序对color_print进行一些更新,例如:
>>> from lazyme.string import palette, highlighter, formatter
>>> from lazyme.string import color_print
>>> palette.keys() # Available colors.
['pink', 'yellow', 'cyan', 'magenta', 'blue', 'gray', 'default', 'black', 'green', 'white', 'red']
>>> highlighter.keys() # Available highlights.
['blue', 'pink', 'gray', 'black', 'yellow', 'cyan', 'green', 'magenta', 'white', 'red']
>>> formatter.keys() # Available formatter,
['hide', 'bold', 'italic', 'default', 'fast_blinking', 'faint', 'strikethrough', 'underline', 'blinking', 'reverse']
注意:斜体、快速闪烁和删除线可能不适用于所有终端,也不适用于Mac和Ubuntu。
例如。,
>>> color_print('foo bar', color='pink', highlight='white')
foo bar
>>> color_print('foo bar', color='pink', highlight='white', reverse=True)
foo bar
>>> color_print('foo bar', color='pink', highlight='white', bold=True)
foo bar
>>> color_print('foo bar', color='pink', highlight='white', faint=True)
foo bar
>>> color_print('foo bar', color='pink', highlight='white', faint=True, reverse=True)
foo bar
>>> color_print('foo bar', color='pink', highlight='white', underline=True, reverse=True)
foo bar
截图:
这里有一个简单的函数,我使用它来打印彩色文本消息,而不必记住ANSI代码,而是使用标准RGB元组来定义前景和背景颜色。
def print_in_color(txt_msg, fore_tuple, back_tuple, ):
# Prints the text_msg in the foreground color specified by fore_tuple with the background specified by back_tuple
# text_msg is the text, fore_tuple is foreground color tuple (r,g,b), back_tuple is background tuple (r,g,b)
rf,bf,gf = fore_tuple
rb,gb,bb = back_tuple
msg = '{0}' + txt_msg
mat = '\33[38;2;' + str(rf) + ';' + str(gf) + ';' + str(bf) + ';48;2;' + str(rb) + ';' +str(gb) + ';' + str(bb) + 'm'
print(msg .format(mat))
print('\33[0m') # Returns default print color to back to black
# Example of use using a message with variables
fore_color = 'cyan'
back_color = 'dark green'
msg = 'foreground color is {0} and the background color is {1}'.format(fore_color, back_color)
print_in_color(msg, (0,255,255), (0,127,127))