如何在Python中将彩色文本输出到终端?
对于Windows,除非使用Win32 API,否则无法使用颜色打印到控制台。
对于Linux,它就像使用打印一样简单,转义序列如下:
颜色
要使字符像方框一样打印,这实际上取决于控制台窗口使用的字体。磅符号效果很好,但它取决于字体:
#
您可以使用curses库的Python实现:curses-字符单元显示的终端处理
此外,运行此程序,您将找到您的盒子:
for i in range(255):
print i, chr(i)
您想了解ANSI转义序列。下面是一个简单的例子:
CSI = "\x1B["
print(CSI+"31;40m" + "Colored Text" + CSI + "0m")
有关详细信息,请参见ANSI转义码。
对于块字符,请尝试使用Unicode字符,如\u2588:
print(u"\u2588")
将所有内容放在一起:
print(CSI+"31;40m" + u"\u2588" + CSI + "0m")
这在某种程度上取决于您所在的平台。最常见的方法是打印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中找到一些位图(用户制作的瓷砖)。
文本模式演示比赛有更多的资源用于在文本模式下制作图形。
如果你正在编程一个游戏,也许你想改变背景颜色,只使用空格?例如:
print " "+ "\033[01;41m" + " " +"\033[01;46m" + " " + "\033[01;42m"
对于字符
您的终端很可能使用Unicode(通常为UTF-8编码)字符,所以只需选择合适的字体即可看到您喜爱的字符。Unicode字符U+2588,“完整块”是我建议您使用的字符。
尝试以下操作:
import unicodedata
fp= open("character_list", "w")
for index in xrange(65536):
char= unichr(index)
try: its_name= unicodedata.name(char)
except ValueError: its_name= "N/A"
fp.write("%05d %04x %s %s\n" % (index, index, char.encode("UTF-8"), its_name)
fp.close()
稍后使用您喜爱的查看器检查文件。
对于颜色
curses是您要使用的模块。查看本教程。
在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)
还有Python termcolor模块。用法很简单:
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')
下面是一个诅咒示例:
import curses
def main(stdscr):
stdscr.clear()
if curses.has_colors():
for i in xrange(1, curses.COLORS):
curses.init_pair(i, i, curses.COLOR_BLACK)
stdscr.addstr("COLOR %d! " % i, curses.color_pair(i))
stdscr.addstr("BOLD! ", curses.color_pair(i) | curses.A_BOLD)
stdscr.addstr("STANDOUT! ", curses.color_pair(i) | curses.A_STANDOUT)
stdscr.addstr("UNDERLINE! ", curses.color_pair(i) | curses.A_UNDERLINE)
stdscr.addstr("BLINK! ", curses.color_pair(i) | curses.A_BLINK)
stdscr.addstr("DIM! ", curses.color_pair(i) | curses.A_DIM)
stdscr.addstr("REVERSE! ", curses.color_pair(i) | curses.A_REVERSE)
stdscr.refresh()
stdscr.getch()
if __name__ == '__main__':
print "init..."
curses.wrapper(main)
答案是Python中所有跨平台着色的Colorama。
它支持Python 3.5+以及Python 2.7。
截至2021 1月,这一数字仍保持不变。
示例代码:
from colorama import init as colorama_init
from colorama import Fore
from colorama import Style
colorama_init()
print(f"This is {Fore.GREEN}color{Style.RESET_ALL}!")
屏幕截图示例:
我编写了一个简单的模块,可在以下网址获得:http://pypi.python.org/pypi/colorconsole
它适用于Windows、Mac OS X和Linux。它在Linux和Mac上使用ANSI,但在Windows上使用对控制台函数的本地调用。你有颜色、光标定位和键盘输入。它不是诅咒的替代品,但如果您需要在简单脚本或ASCII游戏中使用,它可能非常有用。
我最喜欢的方式是使用祝福库(完整披露:我写的)。例如:
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颜色的终端。它还将不可读的转义序列排除在代码之外,同时保持使用简洁。玩得高兴
您可以使用Clint:
from clint.textui import colored
print colored.red('some warning message')
print colored.green('nicely done!')
为了解决这个问题,我创建了一个简单得让人麻木的程序包,用插值颜色代码打印字符串,称为icolor。
icolor包含两个函数:cformat和cprint,每个函数都包含一个字符串和子字符串,这些子字符串被插值以映射到ANSI转义序列。
from icolor import cformat # there is also cprint
cformat("This is #RED;a red string, partially with a #xBLUE;blue background")
'This is \x1b[31ma red string, partially with a \x1b[44mblue background\x1b[0m'
包括所有ANSI颜色(例如#RED;、#BLUE;等)以及#RESET#粗体;以及其他。
背景色具有x前缀,因此绿色背景将为#xGREEN;。
一个人可以用##逃脱#。
鉴于其简单性,最好的文档可能是代码本身。
它在PYPI上,因此可以使用sudo easy_install icolor。
如果您使用的是Windows,那么就在这里!
# Display text on a Windows console
# Windows XP with Python 2.7 or Python 3.2
from ctypes import windll
# Needed for Python2/Python3 diff
try:
input = raw_input
except:
pass
STD_OUTPUT_HANDLE = -11
stdout_handle = windll.kernel32.GetStdHandle(STD_OUTPUT_HANDLE)
# Look at the output and select the color you want.
# For instance, hex E is yellow on black.
# Hex 1E is yellow on blue.
# Hex 2E is yellow on green and so on.
for color in range(0, 75):
windll.kernel32.SetConsoleTextAttribute(stdout_handle, color)
print("%X --> %s" % (color, "Have a fine day!"))
input("Press Enter to go on ... ")
注意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")
https://raw.github.com/fabric/fabric/master/fabric/colors.py
"""
.. versionadded:: 0.9.2
Functions for wrapping strings in ANSI color codes.
Each function within this module returns the input string ``text``, wrapped
with ANSI color codes for the appropriate color.
For example, to print some text as green on supporting terminals::
from fabric.colors import green
print(green("This text is green!"))
Because these functions simply return modified strings, you can nest them::
from fabric.colors import red, green
print(red("This sentence is red, except for " + \
green("these words, which are green") + "."))
If ``bold`` is set to ``True``, the ANSI flag for bolding will be flipped on
for that particular invocation, which usually shows up as a bold or brighter
version of the original color on most terminals.
"""
def _wrap_with(code):
def inner(text, bold=False):
c = code
if bold:
c = "1;%s" % c
return "\033[%sm%s\033[0m" % (c, text)
return inner
red = _wrap_with('31')
green = _wrap_with('32')
yellow = _wrap_with('33')
blue = _wrap_with('34')
magenta = _wrap_with('35')
cyan = _wrap_with('36')
white = _wrap_with('37')
我已经将joeld的答案打包到一个模块中,该模块具有全局函数,我可以在代码中的任何地方使用这些函数。
文件: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")
我的两分钱(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!')
“工作正常!”显示为绿色。
打印一个开始颜色/样式的字符串,然后是字符串,然后以'\x1b[0m'结束颜色/样式更改:
print('\x1b[6;30;42m' + 'Success!' + '\x1b[0m')
使用以下代码获取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://en.wikipedia.org/wiki/ANSI_escape_code#Colors
我使用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'
我编写了一个在Linux、OS X和Windows中处理颜色的模块。它支持所有平台上的所有16种颜色,您可以在不同的时间设置前景和背景颜色,字符串对象可以为len()和.capitalize()等对象提供正常的结果。
https://github.com/Robpol86/colorclass
您可以使用任何语言提供的shell转义字符。这些转义字符以ESC字符开头,后跟一些参数。
例如,要在终端中输出红色“Hello,World!”字符串:
echo "\e[31m Hello, World! \e[0m"
或者从Python脚本:
print("\e[31m Hello world \e[0m")
此外,我写了一篇关于Escape序列的文章,这可能会帮助您更好地理解这个机制。
使用pyfancy。这是一种在终端中进行颜色处理的简单方法!
例子:
print(pyfancy.RED + "Hello Red" + pyfancy.END)
耶!另一个版本
虽然我觉得这个答案很有用,但我做了一些修改。此GitHub Gist是结果
用法
print colors.draw("i'm yellow", bold=True, fg_yellow=True)
此外,还可以包装常用用法:
print colors.error('sorry, ')
https://gist.github.com/Jossef/0ee20314577925b4027f
根据乔尔德的回答,这简直太简单了:
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')
如果您正在使用Django:
>>> from django.utils.termcolors import colorize
>>> print colorize("Hello, World!", fg="blue", bg='red',
... opts=('bold', 'blink', 'underscore',))
Hello World!
>>> help(colorize)
快照:
(我通常在runserver终端上使用彩色输出进行调试,所以我添加了它。)
您可以测试它是否安装在您的机器中:$python-c“import django;print django.VERSION”。要安装它,请查看:如何安装django
试试看!!
另一个包装Python3打印功能的PyPI模块:
https://pypi.python.org/pypi/colorprint
如果您也可以从__future_import-print中使用,它可以在Python2.x中使用。下面是模块PyPI页面中的Python 2示例:
from __future__ import print_function
from colorprint import *
print('Hello', 'world', color='blue', end='', sep=', ')
print('!', color='red', format=['bold', 'blink'])
它输出“你好,世界!”,单词为蓝色,感叹号为粗体红色并闪烁。
试试这个简单的代码
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!")
asciimatics为构建文本UI和动画提供了可移植的支持:
#!/usr/bin/env python
from asciimatics.effects import RandomNoise # $ pip install asciimatics
from asciimatics.renderers import SpeechBubble, Rainbow
from asciimatics.scene import Scene
from asciimatics.screen import Screen
from asciimatics.exceptions import ResizeScreenError
def demo(screen):
render = Rainbow(screen, SpeechBubble('Rainbow'))
effects = [RandomNoise(screen, signal=render)]
screen.play([Scene(effects, -1)], stop_on_resize=True)
while True:
try:
Screen.wrapper(demo)
break
except ResizeScreenError:
pass
Asciicast:
我最终做了这个,我觉得这是最干净的:
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)
定义开始颜色的字符串和结束颜色的字符串。然后打印文本,开始字符串在前面,结束字符串在结尾。
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
截图:
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')
打印:
演示:
# 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))
在线试用
一个更简单的选择是使用termcolor包中的cprint函数。
它还支持%s,%d格式的打印:
结果可能取决于终端,因此请查看软件包文档的“终端财产”部分。
Windows命令提示符和Python IDLE不工作
JupyterLab笔记本确实有效
我是Python新手,每次我发现像这样的主题时都很兴奋。但这次(突然)我觉得我有话要说。尤其是因为几分钟前,我在Python中发现了一件令人惊叹的事情(至少对我来说是这样):
上下文管理器
from contextlib import contextmanager
# FORECOLOR
BLACKFC,REDFC,GREENFC,YELLOWFC,BLUEFC = '38;30m','38;31m','38;32m','38;33m','38;34m'
# BACKGOUND
BLACKBG,REDBG,GREENBG,YELLOWBG,BLUEBG = '48;40m','48;41m','48;42m','48;43m','48;44m'
@contextmanager
def printESC(prefix, color, text):
print("{prefix}{color}{text}".format(prefix=prefix, color=color, text=text), end='')
yield
print("{prefix}0m".format(prefix=prefix))
with printESC('\x1B[', REDFC, 'Colored Text'):
pass
实例
或者就像这样:
# FORECOLOR
BLACKFC,REDFC,GREENFC,YELLOWFC,BLUEFC = '38;30m','38;31m','38;32m','38;33m','38;34m'
# BACKGOUND
BLACKBG,REDBG,GREENBG,YELLOWBG,BLUEBG = '48;40m','48;41m','48;42m','48;43m','48;44m'
def printESC(prefix, color, text):
print("{prefix}{color}{text}".format(prefix=prefix, color=color, text=text), end='')
print("{prefix}0m".format(prefix=prefix))
printESC('\x1B[', REDFC, 'Colored Text')
这里有一个本机适用于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代码,无论是通过系统调用还是模块。并非所有的文字装饰都受支持,虽然显示的是明亮的颜色,但它们与常规颜色相同。
感谢@j-l找到了更短的方法。
tl;dr:添加os.system(“”)
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")
联机尝试
我能找到的最简单的方法不是使用ANSI转义码,而是使用导入模块colorama中的Fore。看看下面的代码:
from colorama import Fore, Style
print(Fore.MAGENTA + "IZZ MAGENTA BRUH.")
print(Style.RESET_ALL + "IZZ BACK TO NORMALZ.")
与ANSI转义码相比:
print("\u001b[31m IZZ RED (NO MAGENTA ON ANSI CODES).\u001b[0m")
print("BACK TO NORMALZ.")
我有一个叫做colorist的图书馆。这非常简单。
以下是一些示例:
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()
这为您提供了:
值得注意的是,这是跨平台的,已经在Mac、Linux和Windows上进行了测试。
你可能想试试:https://github.com/SuperMaZingCoder/colorit
coloret现在可以与PyPi一起安装了!您可以在Windows上使用pipinstall-color-it安装它,在macOS和Linux上使用pip3 install-color-it安装它。
这里有一个简单的函数,我使用它来打印彩色文本消息,而不必记住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))
我建议这个新图书馆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")
在我看来,这是最简单的方法。只要您具有所需颜色的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)
我创建了一个项目(控制台颜色),并已将其发布到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'。
我只是让它易于使用(至少对我来说)。
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库)有一种非常方便的方式来实现这一点,如果您正在编写命令行工具,无论如何都值得考虑。
Rich是一个相对较新的Python库,用于在终端中处理颜色。
在Rich中有几种处理颜色的方法。最快的入门方法是富打印方法,它将类似BBCode的语法呈现到ANSI控制代码中:
from rich import print
print("[red]Color[/] in the [bold magenta]Terminal[/]!")
还有其他方法可以通过Rich(正则表达式、语法)和相关的格式化功能应用颜色。
一些解决方案包括:
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代码,根据您的选择对输出进行着色(但可能需要调用其他特定于系统的函数,以便能够在终端中显示彩色文本)。
这个答案试图通过使用正则表达式为文本块中的关键字着色来扩展将着色文本写入终端的概念。
这个答案还使用了Python库Rich,在前面的问题答案中简要介绍了它。在这个答案中,我使用函数rich.color.ANSI_color_NAMES获取一个随机的颜色列表,用于突出显示预定义的搜索项。
import random
import re as regex
from rich import color
from rich import print
def create_dynamic_regex(search_words):
"""
This function is used to create a dynamic regular expression
string and a list of random colors. Both these elements will
be used in the function colorize_text()
:param search_words: list of search terms
:return: regular expression search string and a list of colors
:rtype: string, list
"""
colors_required = create_list_of_colors(len(search_words))
number_of_search_words = len(search_words)
combined_string = ''
for search_word in search_words:
number_of_search_words -= 1
if number_of_search_words != 0:
current_string = ''.join(r'(\b' + search_word + r'\b)|')
combined_string = (combined_string + current_string)
elif number_of_search_words == 0:
current_string = ''.join(r'(\b' + search_word + r'\b)')
combined_string = (combined_string + current_string)
return combined_string, colors_required
def random_color():
"""
This function is used to create a random color using the
Python package rich.
:return: color name
:rtype: string
"""
selected_color = random.choice(list(color.ANSI_COLOR_NAMES.keys()))
return selected_color
def create_list_of_colors(number_of_colors):
"""
This function is used to generate a list of colors,
which will be used in the function colorize_text()
:param number_of_colors:
:return: list of colors
:rtype: list
"""
list_of_colors = [random_color() for _ in range(number_of_colors)]
return list_of_colors
def colorize_text(text, regex_string, array_of_colors):
"""
This function is used to colorize specific words in a text string.
:param text: text string potentially containing specific words to colorize.
:param regex_string: regular expression search string
:param array_of_colors: list of colors
:return: colorized text
:rtype: string
"""
available_colors = array_of_colors
word_regex = regex.compile(f"{regex_string}", regex.IGNORECASE)
i = 0
output = ""
for word in word_regex.finditer(text):
get_color = available_colors[word.lastindex - 1]
output += "".join([text[i:word.start()],
"[%s]" % available_colors[word.lastindex - 1],
text[word.start():word.end()], "[/%s]" % available_colors[word.lastindex - 1]])
i = word.end()
return ''.join([output, text[word.end():]])
def generate_console_output(text_to_search, words_to_find):
"""
This function is used generate colorized text that will
be outputting to the console.
:param text_to_search: text string potentially containing specific words to colorize.
:param words_to_find: list of search terms.
:return: A string containing colorized words.
:rtype: string
"""
search_terms, colors = create_dynamic_regex(words_to_find)
colorize_html = colorize_text(text_to_search, search_terms, colors)
print(colorize_html)
text = "The dog chased the cat that was looking for the mouse that the dog was playing with."
words = ['dog', 'cat', 'mouse']
generate_console_output(text, words)
以下是上述代码的打印输出:
我创建了两个用于为文本着色的GIST。
彩色文本终端输出彩色文本HTML输出
这是我的现代(2021)解决方案:yachalk
它是少数正确支持嵌套样式的库之一:
除此之外,yachalk是自动完成友好的,具有256/真彩色支持,带有终端功能检测,并且是全类型的。
以下是您在选择解决方案时可能考虑的一些设计决策。
高级库与低级库/手动样式处理?
这个问题的许多答案都演示了如何直接使用ANSI转义代码,或者建议使用需要手动启用/禁用样式的低级库。
这些方法有一些微妙的问题:手动插入打开/关闭样式
语法上更详细,因为必须显式指定重置,更容易出错,因为您可能会意外忘记重置样式,无法正确处理边缘情况:例如,在某些终端中,需要在换行之前重置样式,并在换行后重新激活它们。此外,一些终端在简单地覆盖互斥样式方面存在问题,需要插入“不必要的”重置代码。如果开发者的本地终端没有这些怪癖,开发者不会立即发现这些怪癖。该问题将仅由其他人稍后报告,或导致问题,例如CI终端。
因此,如果要实现与许多终端的兼容性,最好使用提供自动处理样式重置的高级库。这允许库通过在需要时插入“伪”ANSI转义码来处理所有边缘情况。
为什么还有另一个图书馆?
在JavaScript中,任务的实际标准库是粉笔,在JS项目中使用了一段时间后,Python世界中可用的解决方案缺乏可比性。粉笔API不仅使用起来更方便(完全自动完成兼容),它还可以正确处理所有边缘情况。
yachalk的想法是为Python生态系统带来同样的便利。如果您对与其他库的比较感兴趣,我已经在项目页面上开始了功能比较。此外,这里有一长串(但仍然不完整)的备选方案,这些方案是在我的研究中提出的——有很多可供选择:)
有色的安西科色术语颜色科罗拉多州猪圈,猪圈祝福富有的彩色照相机彩色印刷品控制台颜色皮凡奇库勒尔牌手表样式(以前称为clr)皮白垩简单粉笔克洛克白垩质的(古希腊神话中的)古希腊神话
当我在寻找如何为日志上色时,我被谷歌感动了:
彩色原木
安装
pip install coloredlogs
用法
最小使用量:
import logging
import coloredlogs
coloredlogs.install() # install a handler on the root logger
logging.debug('message with level debug')
logging.info('message with level info')
logging.warning('message with level warning')
logging.error('message with level error')
logging.critical('message with level critical')
结果如下:
从消息级调试开始:
import logging
import coloredlogs
coloredlogs.install(level='DEBUG') # install a handler on the root logger with level debug
logging.debug('message with level debug')
logging.info('message with level info')
logging.warning('message with level warning')
logging.error('message with level error')
logging.critical('message with level critical')
结果如下:
隐藏库中的邮件:
import logging
import coloredlogs
logger = logging.getLogger(__name__) # get a specific logger object
coloredlogs.install(level='DEBUG') # install a handler on the root logger with level debug
coloredlogs.install(level='DEBUG', logger=logger) # pass a specific logger object
logging.debug('message with level debug')
logging.info('message with level info')
logging.warning('message with level warning')
logging.error('message with level error')
logging.critical('message with level critical')
结果如下:
设置日志消息格式:
import logging
import coloredlogs
logger = logging.getLogger(__name__) # get a specific logger object
coloredlogs.install(level='DEBUG') # install a handler on the root logger with level debug
coloredlogs.install(level='DEBUG', logger=logger) # pass a specific logger object
coloredlogs.install(
level='DEBUG', logger=logger,
fmt='%(asctime)s.%(msecs)03d %(filename)s:%(lineno)d %(levelname)s %(message)s'
)
logging.debug('message with level debug')
logging.info('message with level info')
logging.warning('message with level warning')
logging.error('message with level error')
logging.critical('message with level critical')
结果如下:
可用的格式属性:
%(asctime)s-发出日志记录调用时,作为人类可读字符串的时间%(created)f-发出日志调用时的浮点时间%(filename)s-文件名%(funcName)s-包含日志记录调用的函数的名称%(hostname)s-系统主机名%(levelname)s-文本日志记录级别%(levelno)s-整数日志记录级别%(lineno)d-发出记录调用的行号%(message)s-传递给日志记录调用的消息(与%(msg)s相同)%(module)s—发出日志记录调用的不带扩展名的文件名%(毫秒)d-发出日志调用的毫秒部分%(msg)s-传递给日志记录调用的消息(与%(Message)s相同)%(name)s-记录器名称%(pathname)s—包含日志记录调用的文件的完整路径名%(process)d-进程ID%(processName)s-进程名称%(programname)s-系统程序名%(relativeCreated)d-发出日志调用时的时间(以毫秒为单位),相对于加载日志模块的时间%(thread)d-线程ID%(threadName)s-线程名称%(username)s-系统用户名
来源:
Coloredlogs包
日志记录库
您可以使用pygments模块来执行此操作。例如:
from pygments import console
print(pygments.console.colorize("red", "This text is red."))
这不允许您为终端提供十六进制颜色,但您可以尝试许多内置颜色,如“蓝色”、“深绿色”、“黄色”等。
在windows 10中,您可以尝试使用这个小脚本,它用作颜色混合器,红色、绿色和蓝色的值为0-255:
import os
os.system('')
def RGB(red=None, green=None, blue=None,bg=False):
if(bg==False and red!=None and green!=None and blue!=None):
return f'\u001b[38;2;{red};{green};{blue}m'
elif(bg==True and red!=None and green!=None and blue!=None):
return f'\u001b[48;2;{red};{green};{blue}m'
elif(red==None and green==None and blue==None):
return '\u001b[0m'
并调用RGB函数使颜色的任意组合为:
g0 = RGB()
g1 = RGB(0,255,0)
g2 = RGB(0,100,0,True)+""+RGB(100,255,100)
g3 = RGB(0,255,0,True)+""+RGB(0,50,0)
print(f"{g1}green1{g0}")
print(f"{g2}green2{g0}")
print(f"{g3}green3{g0}")
不带参数的RGB()将清理并将前景/背景颜色设置为默认值。如果您想要黑色,则应将其称为RGB(0,0,0),白色RGB(255255255)。当RGB(0255,0)创建绝对绿色时,RGB(150255150)将生成浅绿色。
这支持背景色和前景色,要将颜色设置为背景色,必须使用bg=True传递,默认情况下为False。
例如:若要将红色设置为背景色,应将其称为RGB(255,0,0,True),但若要选择红色作为字体颜色,则只需将其命名为RGB(255,0,0,False),因为默认情况下bg为False,这将简化为仅将其称之为RGB(25.5,0,0)
考虑到您是否正在编写命令行工具,这是最简单和方便的方法。这种方法可以在所有控制台上的任何地方工作,而无需安装任何花哨的软件包。
要使ANSI代码在Windows上运行,首先,运行os.system('color')
import os
os.system('color')
COLOR = '\033[91m' # change it, according to the color need
END = '\033[0m'
print(COLOR + "Hello World" + END) #print a message
exit=input() #to avoid closing the terminal windows
更多颜色:
注意:\33[5m和\33[6m闪烁。
感谢@qubodup
最低等级:
class log:
f = lambda color: lambda string: print(color + string + "\33[0m")
black = f("\33[30m")
red = f("\33[31m")
green = f("\33[32m")
yellow = f("\33[33m")
blue = f("\33[34m")
magenta = f("\33[35m")
cyan = f("\33[36m")
white = f("\33[37m")
# Usage
log.blue("Blue World!")
这里有一种更有效的方法。
# Colours
pure_red = "\033[0;31m"
dark_green = "\033[0;32m"
orange = "\033[0;33m"
dark_blue = "\033[0;34m"
bright_purple = "\033[0;35m"
dark_cyan = "\033[0;36m"
dull_white = "\033[0;37m"
pure_black = "\033[0;30m"
bright_red = "\033[0;91m"
light_green = "\033[0;92m"
yellow = "\033[0;93m"
bright_blue = "\033[0;94m"
magenta = "\033[0;95m"
light_cyan = "\033[0;96m"
bright_black = "\033[0;90m"
bright_white = "\033[0;97m"
cyan_back = "\033[0;46m"
purple_back = "\033[0;45m"
white_back = "\033[0;47m"
blue_back = "\033[0;44m"
orange_back = "\033[0;43m"
green_back = "\033[0;42m"
pink_back = "\033[0;41m"
grey_back = "\033[0;40m"
grey = '\033[38;4;236m'
bold = "\033[1m"
underline = "\033[4m"
italic = "\033[3m"
darken = "\033[2m"
invisible = '\033[08m'
reverse_colour = '\033[07m'
reset_colour = '\033[0m'
grey = "\x1b[90m"
用户手册
reverseColor表示您反转刚刚选择的颜色,但处于高亮模式(默认为白色)。pink_back(green_back等…带有back的)表示它以粉色突出显示(基于名称)。reset_colour重置颜色(详见图1)。
我相信我不需要解释太多,因为它列在变量名中。
如果您想尝试代码,请转到replit IDE测试代码。示例代码在这里
代码(图1):
输出(图2):
我编写了一个在PyPI上可用的库,它有一个遵循标准打印函数的简单API。
你可以用pip安装着色来安装它。
import coloring
# Directly use print-like functions
coloring.print_red('Hello', 12)
coloring.print_green('Hey', end="", sep=";")
print()
# Get str as return
print(coloring.red('hello'))
# Use the generic colorize function
print(coloring.colorize("I'm red", "red")) # Using color names
print(coloring.colorize("I'm green", (0, 255, 0))) # Using RGB colors
print(coloring.colorize("I'm blue", "#0000ff")) # Using hex colors
# Or using styles (underline, bold, italic, ...)
print(coloring.colorize('Hello', 'red', s='ub')) # underline and bold
执行代码:
您可以在此处查看所有功能:https://github.com/Nazime/coloring.
作为RGB标准的粉丝,我会这样做:
def color_text(text, rgb):
r, g, b = rgb
return f"\033[38;2;{r};{g};{b}m{text}\033[0m"
class rgb():
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
YELLOW = (255, 255, 0)
# and so on ...
print(color_text("hello colored world", rgb.GREEN))
PS:受到CircuitSacul回答的强烈启发
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
下面是一个可以这样使用的实现:
from stryle import Stryle
print(Stryle.okgreen.bold@"Hello World" + Stryle.underline@'!' + ' back to normal')
print(f"{Stryle.red}Merry {Stryle.underline.okgreen}Christmas!{Stryle.off}")
print("Merry "@Stryle.red + "Christmas"@Stryle.okgreen.underline)
_decorations = {
"header" : '\033[95m',
"okblue" : '\033[94m',
"okcyan" : '\033[96m',
"okgreen" : '\033[92m',
"yellow" : '\033[93m',
"red" : '\033[91m',
"warning" : '\033[93m',
"fail" : '\033[91m',
"off" : '\033[0m',
"bold" : '\033[1m',
"underline" : '\033[4m',
}
class _StringStyle(str):
def __getattribute__(self, decoration: str = _decorations["off"]):
if decoration in _decorations:
return _StringStyle(self.decorations + _decorations[decoration])
return self
def __matmul__(self, other):
return self.decorations + str(other) + _decorations["off"]
def __rmatmul__(self, other):
return self.decorations + str(other) + _decorations["off"]
def __str__(self):
return self.decorations
Stryle = _StringStyle()
这里有一个快速类,它包装了一个打印功能,可以快速添加颜色,而无需安装其他软件包。
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")
输出