如何在Python中将彩色文本输出到终端?
当前回答
import click
click.secho('Hello, World!', fg='green')
click.secho('Some more text', bg='blue', fg='white')
click.secho('ATTENTION', blink=True, bold=True)
click(CLI库)有一种非常方便的方式来实现这一点,如果您正在编写命令行工具,无论如何都值得考虑。
其他回答
我最终做了这个,我觉得这是最干净的:
formatters = {
'RED': '\033[91m',
'GREEN': '\033[92m',
'END': '\033[0m',
}
print 'Master is currently {RED}red{END}!'.format(**formatters)
print 'Help make master {GREEN}green{END} again!'.format(**formatters)
sty类似于colorama,但它不那么冗长,支持8位和24位(RGB)颜色,支持所有效果(粗体、下划线等),允许您注册自己的样式,是完全类型和高性能的,支持静音,不干扰全局设置,如sys.stdout,真的很灵活,文档很好,等等。。。
示例:
from sty import fg, bg, ef, rs
foo = fg.red + 'This is red text!' + fg.rs
bar = bg.blue + 'This has a blue background!' + bg.rs
baz = ef.italic + 'This is italic text' + rs.italic
qux = fg(201) + 'This is pink text using 8bit colors' + fg.rs
qui = fg(255, 10, 10) + 'This is red text using 24bit colors.' + fg.rs
# Add custom colors:
from sty import Style, RgbFg
fg.orange = Style(RgbFg(255, 150, 50))
buf = fg.orange + 'Yay, Im orange.' + fg.rs
print(foo, bar, baz, qux, qui, buf, sep='\n')
打印:
演示:
一些解决方案包括:
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代码,根据您的选择对输出进行着色(但可能需要调用其他特定于系统的函数,以便能够在终端中显示彩色文本)。
这里有一个快速类,它包装了一个打印功能,可以快速添加颜色,而无需安装其他软件包。
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")
输出
如果你正在编程一个游戏,也许你想改变背景颜色,只使用空格?例如:
print " "+ "\033[01;41m" + " " +"\033[01;46m" + " " + "\033[01;42m"
推荐文章
- 将Pandas或Numpy Nan替换为None以用于MysqlDB
- 使用pandas对同一列进行多个聚合
- 使用Python解析HTML
- django MultiValueDictKeyError错误,我如何处理它
- 如何在for循环期间修改列表条目?
- 我如何在Django中创建一个鼻涕虫?
- 没有名为'django.core.urlresolvers'的模块
- 蟒蛇导出环境文件
- Django - makemigrations -未检测到任何更改
- SQLAlchemy:引擎、连接和会话差异
- 在Python Pandas中删除多个列中的所有重复行
- 更改pandas DataFrame中的特定列名
- 将Pandas多索引转换为列
- 熊猫在每组中获得最高的n个记录
- 熊猫数据帧得到每组的第一行