如何在 Python 中将彩色文本输出到终端?
█
唯一的问题是它是扩展的 ASCII,也许你可以使用 http://stackoverflow.com/questions/8465226/using-extended-ascii-codes-with-python
让它工作
这在某种程度上取决于您所在的平台。最常见的方法是打印 ANSI 转义序列。举个简单的例子,下面是 Blender build scripts 中的一些 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 emulation)。有用于设置颜色、移动光标等的 ANSI 代码。
如果您对此感到复杂(如果您正在编写游戏,听起来您就是这样),您应该查看“curses”模块,它为您处理了很多复杂的部分。 Python Curses HowTO 是一个很好的介绍。
如果您不使用扩展 ASCII(即,不在 PC 上),您会被 127 以下的 ASCII 字符卡住,而“#”或“@”可能是您最好的选择。如果您可以确保您的终端使用的是 IBM extended ASCII character set,那么您有更多选择。字符 176、177、178 和 219 是“块字符”。
一些现代的基于文本的程序,例如“Dwarf Fortress”,以图形模式模拟文本模式,并使用经典 PC 字体的图像。您可以在 Dwarf Fortress Wiki 查看 (user-made tilesets) 中找到其中一些可以使用的位图。
Text Mode Demo Contest 有更多资源用于在文本模式下绘制图形。
还有Python termcolor module。用法很简单:
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')
termcolor.COLORS
为您提供颜色列表
os.system('color')
,然后 ANSI 转义序列开始工作。
对于 Python 中的所有跨平台着色,答案是 Colorama。
它支持 Python 3.5+ 以及 Python 2.7。
自 2021 年 1 月起,它得到维护。
示例代码:
from colorama import Fore
from colorama import Style
print(f"This is {Fore.GREEN}color{Style.RESET_ALL}!")
https://i.stack.imgur.com/q3D4W.png
<b>bold</b>
)为终端文本添加样式
打印一个以颜色/样式开头的字符串,然后是字符串,然后以 '\x1b[0m'
结束颜色/样式更改:
print('\x1b[6;30;42m' + 'Success!' + '\x1b[0m')
https://i.stack.imgur.com/RN3MN.png
使用以下代码获取 shell 文本的格式选项表:
def print_format_table():
"""
prints table of formatted text format options
"""
for style in range(8):
for fg in range(30,38):
s1 = ''
for bg in range(40,48):
format = ';'.join([str(style), str(fg), str(bg)])
s1 += '\x1b[%sm %s \x1b[0m' % (format, format)
print(s1)
print('\n')
print_format_table()
明暗示例(完整)
https://i.stack.imgur.com/6otvY.png
明暗示例(部分)
https://i.stack.imgur.com/lZr23.png
参考:https://en.wikipedia.org/wiki/ANSI_escape_code#Colors
定义一个开始颜色的字符串和结束颜色的字符串。然后打印您的文本,开始字符串在前面,结束字符串在末尾。
CRED = '\033[91m'
CEND = '\033[0m'
print(CRED + "Error, does not compute!" + CEND)
这会在 urxvt
中使用 Zenburn 风格的配色方案在 Bash 中生成以下内容:
https://i.stack.imgur.com/Iu3I1.png
通过实验,我们可以得到更多的颜色:
https://i.stack.imgur.com/j7e4i.gif
注意:\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
\33[25m
也应该表示“不闪烁”,而不重置其他样式 - en.wikipedia.org/wiki/…
这是一个原生适用于 Windows 10 的解决方案。
使用系统调用(例如 os.system("")
)允许在命令提示符和 Powershell 中本地打印颜色:
import os
# System call
os.system("")
# Class of different styles
class style():
BLACK = '\033[30m'
RED = '\033[31m'
GREEN = '\033[32m'
YELLOW = '\033[33m'
BLUE = '\033[34m'
MAGENTA = '\033[35m'
CYAN = '\033[36m'
WHITE = '\033[37m'
UNDERLINE = '\033[4m'
RESET = '\033[0m'
print(style.YELLOW + "Hello, World!")
注意:Windows 不完全支持 ANSI 代码,无论是通过系统调用还是模块。并非所有文本装饰都受支持,虽然显示的是亮色,但它们与常规颜色相同。
感谢@jl 找到了一个更短的方法。
tl;dr:添加 os.system("")
if sys.platform.lower() == "win32": os.system('color')
,只需将其替换为 os.system('')
。不需要条件,代码在 Windows 10 和 Linux 中都可以运行(当我测试它时)。如您所见,您不必对 color
进行系统调用。对 dir
、cd
、abcdef
和空字符串的调用都可以正常工作(尽管非空字符串可能会打印您不想看到的输出)。
color
的调用不是关键部分。在 Windows 10 上运行时,正是 os.system(command)
行本身使打印颜色成为可能。“命令”实际上可以是任何东西——甚至只是一个空字符串。
os.system("")
会导致颜色代码起作用?
system("");
(include <stdlib.h>
)之后在Windows中使用ASNI代码运行printf(fmt, ...);
的C中确实打印了彩色文本,我仍然很好奇为什么会这样?
您想了解 ANSI 转义序列。这是一个简短的例子:
CSI = "\x1B["
print(CSI+"31;40m" + "Colored Text" + CSI + "0m")
有关详细信息,请参阅 ANSI escape code。
对于块字符,请尝试使用 Unicode 字符,如 \u2588:
print(u"\u2588")
把它们放在一起:
print(CSI+"31;40m" + u"\u2588" + CSI + "0m")
def d(*v): return '\x1B['+';'.join(map(str, v))+'m'
然后 print ' '.join([d(k,i)+str(i%10)+d(0) for i in range(30,38)+range(40,48) for k in range(2)])
"31;40m"
和 "0m"
的用途是什么?
0m
告诉终端停止使用该颜色。
sty 类似于 colorama,但不那么冗长,支持 8-bit 和 24-bit (RGB) 颜色,支持所有 effects(粗体、下划线等),允许您使用 register your own styles,完全键入并且高性能,支持 muting,不会弄乱 sys.stdout
等全局变量,非常灵活,以及 documented 等等...
例子:
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')
印刷:
https://i.stack.imgur.com/4BIdi.png
演示:
https://i.stack.imgur.com/S8wtO.png
fg.rs
和 bg.rs
分别将前景色和背景色重置为默认值。
我最喜欢的方式是使用 Blessings 库(完全公开:我写的)。例如:
from blessings import Terminal
t = Terminal()
print t.red('This is red.')
print t.bold_bright_red_on_black('Bright red on black')
要打印彩色砖块,最可靠的方法是使用背景颜色打印空间。我使用这种技术在 nose-progressive 中绘制进度条:
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 色终端。它还可以将不可读的转义序列排除在您的代码之外,同时保持简洁易用。玩得开心!
getattr
轻松地将其设为参数。或者更有可能,只是动态地创建格式字符串。
can just pass
是一个 python 函数。
我使用 for
循环生成了一个包含所有颜色的类,以迭代每个颜色组合,最多可达 100,然后用 Python 颜色编写了一个类。随意复制和粘贴,我的 GPLv2:
class colors:
'''Colors class:
Reset all colors with colors.reset
Two subclasses fg for foreground and bg for background.
Use as colors.subclass.colorname.
i.e. colors.fg.red or colors.bg.green
Also, the generic bold, disable, underline, reverse, strikethrough,
and invisible work with the main class
i.e. colors.bold
'''
reset='\033[0m'
bold='\033[01m'
disable='\033[02m'
underline='\033[04m'
reverse='\033[07m'
strikethrough='\033[09m'
invisible='\033[08m'
class fg:
black='\033[30m'
red='\033[31m'
green='\033[32m'
orange='\033[33m'
blue='\033[34m'
purple='\033[35m'
cyan='\033[36m'
lightgrey='\033[37m'
darkgrey='\033[90m'
lightred='\033[91m'
lightgreen='\033[92m'
yellow='\033[93m'
lightblue='\033[94m'
pink='\033[95m'
lightcyan='\033[96m'
class bg:
black='\033[40m'
red='\033[41m'
green='\033[42m'
orange='\033[43m'
blue='\033[44m'
purple='\033[45m'
cyan='\033[46m'
lightgrey='\033[47m'
在我看来,这是最简单的方法。只要你有你想要的颜色的 RGB 值,这应该可以工作:
def colored(r, g, b, text):
return f"\033[38;2;{r};{g};{b}m{text}\033[0m"
打印红色文本的示例:
text = 'Hello, World!'
colored_text = colored(255, 0, 0, text)
print(colored_text)
#or
print(colored(255, 0, 0, 'Hello, World!'))
多色文本
text = colored(255, 0, 0, 'Hello, ') + colored(0, 255, 0, 'World')
print(text)
试试这个简单的代码
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!")
https://i.stack.imgur.com/VsUHx.png
# 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!")
def prGreen: return '"\033[91m {}\033[00m" .format(prt)
,它是这样使用的:print(f'This will turn {prGreen("Hello world")} and change back')
我有一个 library called colorit。超级简单。
这里有些例子:
from colorit import *
# Use this to ensure that ColorIt will be usable by certain command line interfaces
# Note: This clears the terminal
init_colorit()
# Foreground
print(color("This text is red", Colors.red))
print(color("This text is orange", Colors.orange))
print(color("This text is yellow", Colors.yellow))
print(color("This text is green", Colors.green))
print(color("This text is blue", Colors.blue))
print(color("This text is purple", Colors.purple))
print(color("This text is white", Colors.white))
# Background
print(background("This text has a background that is red", Colors.red))
print(background("This text has a background that is orange", Colors.orange))
print(background("This text has a background that is yellow", Colors.yellow))
print(background("This text has a background that is green", Colors.green))
print(background("This text has a background that is blue", Colors.blue))
print(background("This text has a background that is purple", Colors.purple))
print(background("This text has a background that is white", Colors.white))
# Custom
print(color("This color has a custom grey text color", (150, 150, 150)))
print(background("This color has a custom grey background", (150, 150, 150)))
# Combination
print(
background(
color("This text is blue with a white background", Colors.blue), Colors.white
)
)
# If you are using Windows Command Line, this is so that it doesn't close immediately
input()
这给了你:
https://i.stack.imgur.com/AESCH.png
还值得注意的是,这是跨平台的,并且已经在 Mac、Linux 和 Windows 上进行了测试。
您可能想尝试一下:https://github.com/SuperMaZingCoder/colorit
colorit
现在可以与 PyPi 一起安装!您可以在 Windows 上使用 pip install color-it
安装它,在 macOS 和 Linux 上使用 pip3 install color-it
安装它。
pip3
(或 pip
)一起安装。命令为 pip3 install color-it
或 pip install color-it
,可以使用 import colorit
导入。
init_colorit()
语句,它可能是您的终端。它在其他终端有什么作用?
# Pure Python 3.x demo, 256 colors
# Works with bash under Linux and MacOS
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)
# Simple usage: print(fg("text", 160))
https://i.stack.imgur.com/qqMmX.png
"\33[38;5;"
的解释。
'\33'
是转义字符(八进制)。
在 Windows 上,您可以使用模块“win32console”(在某些 Python 发行版中可用)或模块“ctypes”(Python 2.5 及更高版本)来访问 Win32 API。
要查看支持这两种方式的完整代码,请参阅 Testoob 中的 color console reporting code。
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)
我已将 joeld's answer 包装到一个具有全局函数的模块中,我可以在代码中的任何位置使用这些函数。
文件:log.py
def enable():
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = "\033[1m"
def disable():
HEADER = ''
OKBLUE = ''
OKGREEN = ''
WARNING = ''
FAIL = ''
ENDC = ''
def infog(msg):
print(OKGREEN + msg + ENDC)
def info(msg):
print(OKBLUE + msg + ENDC)
def warn(msg):
print(WARNING + msg + ENDC)
def err(msg):
print(FAIL + msg + ENDC)
enable()
使用如下:
import log
log.info("Hello, World!")
log.err("System Error")
def black(text):
print('\033[30m', text, '\033[0m', sep='')
def red(text):
print('\033[31m', text, '\033[0m', sep='')
def green(text):
print('\033[32m', text, '\033[0m', sep='')
def yellow(text):
print('\033[33m', text, '\033[0m', sep='')
def blue(text):
print('\033[34m', text, '\033[0m', sep='')
def magenta(text):
print('\033[35m', text, '\033[0m', sep='')
def cyan(text):
print('\033[36m', text, '\033[0m', sep='')
def gray(text):
print('\033[90m', text, '\033[0m', sep='')
black("BLACK")
red("RED")
green("GREEN")
yellow("YELLOW")
blue("BLACK")
magenta("MAGENTA")
cyan("CYAN")
gray("GRAY")
我最终这样做了,我觉得它是最干净的:
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)
这是我的现代 (2021) 解决方案:yachalk
它是为数不多的正确支持嵌套样式的库之一:
https://i.stack.imgur.com/piYe5.png
除此之外,yachalk 是自动完成友好的,支持 256/真彩色,带有终端功能检测,并且是全类型的。
以下是您在选择解决方案时可能会考虑的一些设计决策。
高级库与低级库/手动样式处理?
这个问题的许多答案演示了如何直接转义 ANSI 代码,或建议需要手动启用/禁用样式的低级库。
这些方法有一些微妙的问题:手动插入开/关样式是
在语法上更详细,因为必须明确指定重置,
更容易出错,因为您可能会不小心忘记重置样式,
无法正确处理边缘情况:例如,在某些终端中,必须在换行之前重置样式,并在换行后重新激活它们。此外,一些终端在简单地覆盖互斥样式方面存在问题,并且需要插入“不必要的”重置代码。如果开发者的本地终端没有这些怪癖,开发者不会立即发现这些怪癖。该问题只会在稍后由其他人报告或导致问题,例如在 CI 终端上。
因此,如果与许多终端兼容是一个目标,最好使用提供自动处理样式重置的高级库。这允许库通过在需要的地方插入“虚假”ANSI 转义码来处理所有边缘情况。
为什么还有一个图书馆?
在 JavaScript 中,该任务的事实上的标准库是 chalk,在 JS 项目中使用了一段时间后,与之相比,Python 世界中可用的解决方案缺乏。 chalk API 不仅使用起来更方便(完全兼容自动完成),它还可以正确处理所有边缘情况。
yachalk 的想法是为 Python 生态系统带来同样的便利。如果您有兴趣与其他库进行比较,我已在项目页面上开始feature comparison。此外,这里有一个很长(但仍然不完整)的替代品清单,这些替代品在我的研究过程中出现——有很多可供选择:)
有色
异色
术语颜色
颜色
麦粒肿
祝福
富有的
颜色
彩印
控制台颜色
玩偶
颜色
样式(以前称为 clr)
pychalk
简单的粉笔
chlk
白垩
非常简单,基于 joeld's answer:
class PrintInColor:
RED = '\033[91m'
GREEN = '\033[92m'
YELLOW = '\033[93m'
LIGHT_PURPLE = '\033[94m'
PURPLE = '\033[95m'
END = '\033[0m'
@classmethod
def red(cls, s, **kwargs):
print(cls.RED + s + cls.END, **kwargs)
@classmethod
def green(cls, s, **kwargs):
print(cls.GREEN + s + cls.END, **kwargs)
@classmethod
def yellow(cls, s, **kwargs):
print(cls.YELLOW + s + cls.END, **kwargs)
@classmethod
def lightPurple(cls, s, **kwargs):
print(cls.LIGHT_PURPLE + s + cls.END, **kwargs)
@classmethod
def purple(cls, s, **kwargs):
print(cls.PURPLE + s + cls.END, **kwargs)
然后就
PrintInColor.red('hello', end=' ')
PrintInColor.green('world')
print
-replacements?异议被撤销。
print
这样通用的功能,应该确保正确复制其功能。
def purple(cls, *args, **kwargs): print(cls.PURPLE, *args, cls.END, **kwargs)
</code>
以 joeld's answer 为基础,使用 https://pypi.python.org/pypi/lazyme
pip install -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
截屏:
https://i.stack.imgur.com/9NgeB.png
使用新格式化程序对 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']
注意:italic
、fast blinking
和 strikethrough
可能无法在所有终端上运行,并且它们不适用于 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
截屏:
https://i.stack.imgur.com/HGNPc.png
请注意 with
关键字与需要重置的修饰符(使用 Python 3 和 Colorama)的混合效果:
from colorama import Fore, Style
import sys
class Highlight:
def __init__(self, clazz, color):
self.color = color
self.clazz = clazz
def __enter__(self):
print(self.color, end="")
def __exit__(self, type, value, traceback):
if self.clazz == Fore:
print(Fore.RESET, end="")
else:
assert self.clazz == Style
print(Style.RESET_ALL, end="")
sys.stdout.flush()
with Highlight(Fore, Fore.GREEN):
print("this is highlighted")
print("this is not")
print(Style.BRIGHT + "Header Test")
和 print (Style.DIM + word)
创建了一个非常好的提示。
contextlib
。
@contextlib.contextmanager
装饰器,不是吗?
您可以使用 Clint:
from clint.textui import colored
print colored.red('some warning message')
print colored.green('nicely done!')
您可以使用 curses 库的 Python 实现:curses — Terminal handling for character-cell displays
另外,运行这个,你会找到你的盒子:
for i in range(255):
print i, chr(i)
如果您正在编写游戏,也许您想更改背景颜色并仅使用空格?例如:
print " "+ "\033[01;41m" + " " +"\033[01;46m" + " " + "\033[01;42m"
更简单的选择是使用 termcolor
包中的 cprint
函数。
https://i.stack.imgur.com/v35jK.png
它还支持%s, %d
格式的打印:
https://i.stack.imgur.com/BvgXH.png
结果可能取决于终端,因此请查看包文档的终端属性部分。
Windows 命令提示符和 Python IDLE 不起作用
https://i.stack.imgur.com/46mp4.png
https://i.stack.imgur.com/4A7ug.png
JupyterLab 笔记本确实有效
https://i.stack.imgur.com/kFhyO.png
表情符号
您可以像其他人在他们的答案中提到的那样使用文本颜色来获得带有背景或前景色的彩色文本。
但是您可以改用表情符号!例如,您可以将 ⚠️
用于警告消息,将 🛑
用于错误消息。
或者简单地将这些笔记本用作颜色:
📕: error message
📙: warning message
📗: ok status message
📘: action message
📓: canceled status message
📔: Or anything you like and want to recognize immediately by color
🎁 奖励:
此方法还可以帮助您直接在源代码中快速扫描和查找日志。
但是某些操作系统(包括某些版本中带有一些窗口管理器的某些 Linux 发行版)默认表情符号字体默认不是彩色的,您可能希望首先使它们彩色。
如何打开表情符号选择器?
mac os: 控制 + 命令 + 空格
windows: win + .
linux: control + . 或 control + ;
耶!另一个版本
虽然我发现 this answer 有用,但我对其进行了一些修改。这个 GitHub Gist 是结果
用法
print colors.draw("i'm yellow", bold=True, fg_yellow=True)
https://i.stack.imgur.com/q1mJ3.png
此外,您可以包装常见的用法:
print colors.error('sorry, ')
https://i.stack.imgur.com/uGgd7.png
https://gist.github.com/Jossef/0ee20314577925b4027f
不定期副业成功案例分享
tput
、like so,因为它会产生更多可移植的代码。disable
的一个真正用例是将输出通过管道传输到文件时;虽然像cat
这样的工具可能支持颜色,但通常最好不要将颜色信息打印到文件中。import ctypes;
kernel32 = ctypes.WinDLL('kernel32');
hStdOut = kernel32.GetStdHandle(-11);
mode = ctypes.c_ulong();
kernel32.GetConsoleMode(hStdOut, ctypes.byref(mode));
mode.value |= 4;
kernel32.SetConsoleMode(hStdOut, mode)
。