joe*_*eld 1655
这在某种程度上取决于您所处的平台.最常见的方法是打印ANSI转义序列.举一个简单的例子,这里有一些来自blender构建脚本的 python代码:
class bcolors:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
Run Code Online (Sandbox Code Playgroud)
要使用这样的代码,你可以做类似的事情
print bcolors.WARNING + "Warning: No active frommets remain. Continue?"
+ bcolors.ENDC
Run Code Online (Sandbox Code Playgroud)
这将适用于包括OS X,Linux和Windows的unix(如果您使用ANSICON,或者在Windows 10中,只要您启用VT100仿真).有ansi代码用于设置颜色,移动光标等.
如果你要复杂化这个(如果你正在编写一个游戏,听起来就是这样),你应该查看"curses"模块,它可以为你处理很多复杂的部分.在Python的诅咒HOWTO是一个很好的介绍.
如果你没有使用扩展的ASCII(即不在PC上),那么你会遇到127以下的ascii字符,而'#'或'@'可能是你阻止的最佳选择.如果您可以确保您的终端使用IBM 扩展的ascii字符集,那么您还有更多选择.字符176,177,178和219是"块字符".
一些现代的基于文本的程序,如"矮人要塞",在图形模式下模拟文本模式,并使用经典PC字体的图像.您可以在Dwarf Fortress Wiki上找到一些可以使用的位图(用户自制的tilesets).
在文本模式设计大赛已在文本模式下做图形更多的资源.
嗯......我觉得这个答案有点过分了.不过,我正在计划一个史诗般的基于文本的冒险游戏.祝你的彩色文字好运!
Sam*_*ain 723
我很惊讶没人提到Python termcolor模块.用法非常简单:
from termcolor import colored
print colored('hello', 'red'), colored('world', 'green')
Run Code Online (Sandbox Code Playgroud)
或者在Python 3中:
print(colored('hello', 'red'), colored('world', 'green'))
Run Code Online (Sandbox Code Playgroud)
然而,对于游戏编程和你想要做的"彩色块"来说,它可能不够复杂......
pri*_*stc 650
答案是Colorama用于Python中的所有跨平台着色.
rab*_*tam 390
打印一个字符串,开始一个颜色/样式,然后打印字符串,然后结束颜色/样式更改'\x1b[0m':
print('\x1b[6;30;42m' + 'Success!' + '\x1b[0m')
Run Code Online (Sandbox Code Playgroud)
使用以下代码获取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()
Run Code Online (Sandbox Code Playgroud)

qub*_*dup 176
定义一个开始颜色的字符串和一个结束颜色的字符串,然后使用前面的起始字符串和结尾处的结束字符串打印文本.
CRED = '\033[91m'
CEND = '\033[0m'
print(CRED + "Error, does not compute!" + CEND)
Run Code Online (Sandbox Code Playgroud)
这产生以下内容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'
Run Code Online (Sandbox Code Playgroud)
以下是生成测试的代码:
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
Run Code Online (Sandbox Code Playgroud)
Bry*_*ley 86
您想了解ANSI转义序列.这是一个简短的例子:
CSI="\x1B["
print(CSI+"31;40m" + "Colored Text" + CSI + "0m")
Run Code Online (Sandbox Code Playgroud)
有关详细信息,请参阅http://en.wikipedia.org/wiki/ANSI_escape_code
对于块字符,请尝试像\ u2588这样的unicode字符:
print(u"\u2588")
Run Code Online (Sandbox Code Playgroud)
把它们放在一起:
print(CSI+"31;40m" + u"\u2588" + CSI + "0m")
Run Code Online (Sandbox Code Playgroud)
Wil*_*gan 63
Rich是一个相对较新的 Python 库,用于在终端中处理颜色。
在 Rich 中有几种处理颜色的方法。最快的入门方法是丰富的打印方法,它将类似BBCode的语法呈现为 ANSI 控制代码:
from rich import print
print("[red]Color[/] in the [bold magenta]Terminal[/]!")
Run Code Online (Sandbox Code Playgroud)
还有其他使用 Rich(正则表达式、语法)和相关格式功能应用颜色的方法。
小智 60
我最喜欢的方式是祝福图书馆(完全披露:我写了它).例如:
from blessings import Terminal
t = Terminal()
print t.red('This is red.')
print t.bold_bright_red_on_black('Bright red on black')
Run Code Online (Sandbox Code Playgroud)
要打印彩色砖块,最可靠的方法是打印带有背景颜色的空间.我使用这种技术在nose-progressive中绘制进度条:
print t.on_green(' ')
Run Code Online (Sandbox Code Playgroud)
您也可以在特定位置打印:
with t.location(0, 5):
print t.on_yellow(' ')
Run Code Online (Sandbox Code Playgroud)
如果您在游戏过程中不得不使用其他终端功能,那么您也可以这样做.您可以使用Python的标准字符串格式来保持其可读性:
print '{t.clear_eol}You just cleared a {t.bold}whole{t.normal} line!'.format(t=t)
Run Code Online (Sandbox Code Playgroud)
祝福Blessings的好处是它尽力在各种终端上工作,而不仅仅是(绝大多数)ANSI颜色的终端.它还保留了代码中不可读的转义序列,同时保持简洁易用.玩得开心!
小智 52
使用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'
Run Code Online (Sandbox Code Playgroud)
Rot*_*eti 50
sty类似于colorama,但它不那么冗长,支持8bit和24bit(rgb)颜色,允许您注册自己的颜色,非常灵活且记录良好.
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')
Run Code Online (Sandbox Code Playgroud)
打印:
day*_*v89 44
试试这个简单的代码
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")
Run Code Online (Sandbox Code Playgroud)
Bea*_*der 42
我有一个名为 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()
Run Code Online (Sandbox Code Playgroud)
这给你:
还值得注意的是,这是跨平台的,并且已经在 Mac、Linux 和 Windows 上进行了测试。
您可能想尝试一下:https : //github.com/SuperMaZingCoder/colorit
colorit现在可以与 PyPi 一起安装了!您可以pip install color-it在 Windows 以及pip3 install color-itmacOS 和 Linux 上安装它。
ori*_*rip 32
在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)
Run Code Online (Sandbox Code Playgroud)
Sim*_*ary 26
我之所以做出回应,是因为我找到了一种在Windows上使用ANSI代码的方法,这样您就可以更改文本的颜色而无需任何内置模块:
进行此操作的行是os.system('color'),但是要确保如果此人不在Windows上,则不会引起错误,您可以使用以下脚本:
import os, sys
if sys.platform.lower() == "win32":
os.system('color')
# Group of Different functions for different styles
class style():
BLACK = lambda x: '\033[30m' + str(x)
RED = lambda x: '\033[31m' + str(x)
GREEN = lambda x: '\033[32m' + str(x)
YELLOW = lambda x: '\033[33m' + str(x)
BLUE = lambda x: '\033[34m' + str(x)
MAGENTA = lambda x: '\033[35m' + str(x)
CYAN = lambda x: '\033[36m' + str(x)
WHITE = lambda x: '\033[37m' + str(x)
UNDERLINE = lambda x: '\033[4m' + str(x)
RESET = lambda x: '\033[0m' + str(x)
print(style.YELLOW("Hello, ") + style.RESET("World!"))
Run Code Online (Sandbox Code Playgroud)
Python版本: 3.6.7(32位)
zah*_*anm 23
根据@ joeld的回答,愚蠢的简单
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)
Run Code Online (Sandbox Code Playgroud)
然后就是
PrintInColor.red('hello', end=' ')
PrintInColor.green('world')
Run Code Online (Sandbox Code Playgroud)
L D*_*L D 23
在我看来,这是最简单的方法。只要你有你想要的颜色的 RGB 值,这应该有效:
def colored(r, g, b, text):
return "\033[38;2;{};{};{}m{} \033[38;2;255;255;255m".format(r, g, b, text)
Run Code Online (Sandbox Code Playgroud)
打印红色文本的示例:
text = 'Hello, World!'
colored_text = colored(255, 0, 0, text)
print(colored_text)
#or
print(colored(255, 0, 0, 'Hello, World!'))
Run Code Online (Sandbox Code Playgroud)
多色文字
text = colored(255, 0, 0, 'Hello, ') + colored(0, 255, 0, 'World')
print(text)
Run Code Online (Sandbox Code Playgroud)
Moh*_*amy 22
我已经将@joeld的答案包装到一个具有全局函数的模块中,我可以在代码中的任何地方使用它.
file:log.py
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
Run Code Online (Sandbox Code Playgroud)
用法如下:
import log
log.info("Hello World")
log.err("System Error")
Run Code Online (Sandbox Code Playgroud)
Ube*_*per 20
对于Windows,除非使用win32api,否则无法使用颜色打印到控制台.
对于Linux来说,它就像使用print一样简单,其中包含了转义序列:
对于像盒子一样打印的字符,它实际上取决于您用于控制台窗口的字体.英镑符号效果很好,但它取决于字体:
#
Run Code Online (Sandbox Code Playgroud)
Ben*_*174 20
我最终做到了这一点,我觉得它最干净:
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)
Run Code Online (Sandbox Code Playgroud)
alv*_*vas 19
建立在@joeld的答案上,使用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
Run Code Online (Sandbox Code Playgroud)
截图:
对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']
Run Code Online (Sandbox Code Playgroud)
注意: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
Run Code Online (Sandbox Code Playgroud)
截图:
Gia*_*ava 17
你可以使用CLINT:
from clint.textui import colored
print colored.red('some warning message')
print colored.green('nicely done!')
Run Code Online (Sandbox Code Playgroud)
Jan*_*sen 17
注意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")
Run Code Online (Sandbox Code Playgroud)
dah*_*ron 16
您可以使用curses库的Python实现:http: //docs.python.org/library/curses.html
此外,运行此,你会找到你的盒子:
for i in range(255):
print i, chr(i)
Run Code Online (Sandbox Code Playgroud)
And*_*kha 16
# 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))
Run Code Online (Sandbox Code Playgroud)
小智 14
考虑到您是否正在编写命令行工具,这是最简单方便的方法。此方法适用于所有控制台上的任何位置,无需安装任何精美的软件包。
要让 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
Run Code Online (Sandbox Code Playgroud)
如需更多颜色:
注意:\33[5m 和 \33[6m 闪烁。
感谢@qubodup
小智 13
如果您正在编写游戏,或许您想要更改背景颜色并仅使用空格?例如:
print " "+ "\033[01;41m" + " " +"\033[01;46m" + " " + "\033[01;42m"
Run Code Online (Sandbox Code Playgroud)
Moj*_*ini 11
您可以使用其他人在答案中提到的文本颜色,以获得带有背景或前景色的彩色文本。
但是您可以使用表情符号代替!例如,您可以??用于警告消息和错误消息。
或者简单地将这些笔记本用作颜色:
: error message
: warning message
: ok status message
: action message
: canceled status message
: Or anything you like and want to recognize immediately by color
Run Code Online (Sandbox Code Playgroud)
这种方法还可以帮助您直接在源代码中快速扫描和查找日志。
但是一些操作系统(包括一些带有一些窗口管理器的某些版本的一些 Linux 发行版)默认的表情符号字体默认不是彩色的,你可能首先想让它们变得彩色。
Vin*_*tav 11
ANSI 转义序列是带内信令的标准,用于控制视频文本终端和终端仿真器上的 、cursor location、和其他选项。某些字节序列(大多数以 ASCII 转义字符和括号字符开头)嵌入到文本中。终端将这些序列解释为命令,而不是逐字显示的文本。colorfont styling
根据维基百科文章,我们使用38和48来设置背景颜色,方法是传入2;r;g;b下面的示例 1Html Hex colors ,并在示例 2中使用相同的值
在Windows 10和其他支持 ANSI 转义码的终端中,您可以尝试这个名为 的小脚本holi.py,它用作颜色混合器,红色、绿色和蓝色的值范围为 0-255:
# filename: holi.py
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'
Run Code Online (Sandbox Code Playgroud)
并调用 RGB 函数来进行任意颜色组合:
from holi import *
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}")
Run Code Online (Sandbox Code Playgroud)
RGB()不带参数将清理并将前景色/背景色设置为默认值。如果您想要黑色,您应该将其RGB(0,0,0)称为白色 RGB(255,255,255)。RGB(0,255,0)在创造绝对绿色的 同时RGB(150,255,150)会产生浅绿色。
它支持背景色和前景色,要将颜色设置为背景色,您必须传递它,默认情况下bg=True。False
例如:要设置红色作为背景颜色,它应该被称为RGB(255,0,0,True),但选择红色作为字体颜色,只需调用它,RGB(255,0,0,False)因为bg默认情况下False,这简化为仅将其称为RGB(255,0,0)
如果您不知道如何使用 3 个不同的值而是使用html hex colors您可以尝试以下方法
# filename: holi.py
import os
os.system('')
def HRGB(value=None,bg=False):
if(value==None):
return '\u001b[0m'
value = value.lstrip('#')
lv = len(value)
rgb = tuple(int(value[i:i + lv // 3], 16) for i in range(0, lv, lv // 3))
if(bg==False):
return f'\u001b[38;2;{rgb[0]};{rgb[1]};{rgb[2]}m'
elif(bg==True):
return f'\u001b[48;2;{rgb[0]};{rgb[1]};{rgb[2]}m'
Run Code Online (Sandbox Code Playgroud)
所以你可以再次使用上面相同的例子:
from holi import *
g0 = HRGB()
g1 = HRGB("#00FF00")
g2 = HRGB("#006400",True)+""+ HRGB("#64FF64")
g3 = HRGB("#00FF00",True)+""+ HRGB("#003200")
print(f"{g1}green1{g0}")
print(f"{g2}green2{g0}")
print(f"{g3}green3{g0}")
Run Code Online (Sandbox Code Playgroud)
它产生相同的结果。
您可以选择两个版本(rgb/hex)中的任何一个而不是保存并import holi获得所需的效果
Nav*_*web 10
如果你使用的是Windows,那么就去吧!
# display text on a Windows console
# Windows XP with Python27 or Python32
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 ... ")
Run Code Online (Sandbox Code Playgroud)
Vis*_*hal 10
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')
Run Code Online (Sandbox Code Playgroud)
jfs*_*jfs 10
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
Run Code Online (Sandbox Code Playgroud)
Asciicast:
ijo*_*eph 10
import click
click.secho('Hello, World!', fg='green')
click.secho('Some more text', bg='blue', fg='white')
click.secho('ATTENTION', blink=True, bold=True)
Run Code Online (Sandbox Code Playgroud)
click(CLI 库)有一种非常方便的方法来执行此操作,无论如何,如果您正在编写命令行工具,则值得考虑。
Jak*_*erp 10
您可以找到多个出色的 Python 包来解决您的问题,因此您不必从头开始构建它。坦白说,我是Colorist包的作者。Colorist是轻量级的且不那么冗长。只需使用以下命令安装软件包并pip install colorist输入:
from colorist import red
red("some text in red color")
Run Code Online (Sandbox Code Playgroud)
有时您可能想要对终端样式有更多的控制,所以您也可以这样做:
from colorist import Color
print(f"Only {Color.CYAN}this part{Color.OFF} is in colour")
Run Code Online (Sandbox Code Playgroud)
此外,如果您的终端支持高级 ANSI 颜色,Colorist还支持定义为 RGB、HSL 或 Hex 的颜色:
from colorist import ColorRGB, BgColorRGB
dusty_pink = ColorRGB(194, 145, 164)
bg_steel_blue = BgColorRGB(70, 130, 180)
print(f"I want to use {dusty_pink}dusty pink{dusty_pink.OFF} and {bg_steel_blue}steel blue{bg_steel_blue.OFF} colors inside this paragraph")
Run Code Online (Sandbox Code Playgroud)
from colorist import ColorHSL, BgColorHSL
mustard_green = ColorHSL(60, 56, 43)
bg_steel_gray = BgColorHSL(190, 2, 49)
print(f"I want to use {mustard_green}mustard green{mustard_green.OFF} and {bg_steel_gray}steel blue{bg_steel_gray.OFF} colors inside this paragraph")
Run Code Online (Sandbox Code Playgroud)
from colorist import ColorHex, BgColorHex
watermelon_red = ColorHex("#ff5733")
bg_mint_green = BgColorHex("#99ff99")
print(f"I want to use {watermelon_red}watermelon pink{watermelon_red.OFF} and {bg_mint_green}mint green{bg_mint_green.OFF} colors inside this paragraph")
Run Code Online (Sandbox Code Playgroud)
这是一个curses示例:
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)
Run Code Online (Sandbox Code Playgroud)
虽然我觉得这个答案很有用,但我修改了一下.这个Github Gist就是结果
用法
print colors.draw("i'm yellow", bold=True, fg_yellow=True)
Run Code Online (Sandbox Code Playgroud)

此外,你可以包装常见的用法:
print colors.error('sorry, ')
Run Code Online (Sandbox Code Playgroud)

另一个包装python 3打印功能的pypi模块:
https://pypi.python.org/pypi/colorprint
如果你也可以在python 2.x中使用它from __future__ import print.这是模块pypi页面中的python 2示例:
from __future__ import print_function
from colorprint import *
print('Hello', 'world', color='blue', end='', sep=', ')
print('!', color='red', format=['bold', 'blink'])
Run Code Online (Sandbox Code Playgroud)
输出"Hello,world!" 用蓝色的字和感叹号大胆的红色和闪烁.
如果您只想使用内置包,请遵循以下结构:
实际上,我增强了Mohamed Samy 的答案,它现在负责多个输入和数字。此外,它还支持其他print()参数,例如end=. 此外,我还添加了一个.store()方法,以便将日志也写入文件。
您可以创建一个实用程序以在代码中的任何位置使用它:
# utility.py
from datetime import datetime
class ColoredPrint:
def __init__(self):
self.PINK = '\033[95m'
self.OKBLUE = '\033[94m'
self.OKGREEN = '\033[92m'
self.WARNING = '\033[93m'
self.FAIL = '\033[91m'
self.ENDC = '\033[0m'
def disable(self):
self.PINK = ''
self.OKBLUE = ''
self.OKGREEN = ''
self.WARNING = ''
self.FAIL = ''
self.ENDC = ''
def store(self):
date = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
with open('logfile.log', mode='a') as file_:
file_.write(f"{self.msg} -- {date}")
file_.write("\n")
def success(self, *args, **kwargs):
self.msg = ' '.join(map(str, args))
print(self.OKGREEN + self.msg + self.ENDC, **kwargs)
return self
def info(self, *args, **kwargs):
self.msg = ' '.join(map(str, args))
print(self.OKBLUE + self.msg + self.ENDC, **kwargs)
return self
def warn(self, *args, **kwargs):
self.msg = ' '.join(map(str, args))
print(self.WARNING + self.msg + self.ENDC, **kwargs)
return self
def err(self, *args, **kwargs):
self.msg = ' '.join(map(str, args))
print(self.FAIL + self.msg + self.ENDC, **kwargs)
return self
def pink(self, *args, **kwargs):
self.msg = ' '.join(map(str, args))
print(self.PINK + self.msg + self.ENDC, **kwargs)
return self
Run Code Online (Sandbox Code Playgroud)
例如
from utility import ColoredPrint
log = ColoredPrint()
log.success("Hello" , 123, "Bye").store()
log.info("Hello" , 123, "Bye")
log.warn("Hello" , 123, "Bye")
log.err("Hello" , 123, "Bye").store()
log.pink("Hello" , 123, "Bye")
Run Code Online (Sandbox Code Playgroud)
出去:
[更新]:
现在,它的 PyPI包可用:
pip install python-colored-print
Run Code Online (Sandbox Code Playgroud)
如果你使用Django
>>> from django.utils.termcolors import colorize
>>> print colorize("Hello World!", fg="blue", bg='red',
... opts=('bold', 'blink', 'underscore',))
Hello World!
>>> help(colorize)
Run Code Online (Sandbox Code Playgroud)
快照:

(我通常在runserver终端上使用彩色输出进行调试,所以我添加了它.)
您可以测试它是否已安装在您的计算机中:
$ python -c "import django; print django.VERSION"
要安装它,请检查:如何安装Django
试试看!!
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")
Run Code Online (Sandbox Code Playgroud)
最小班级:
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!")
Run Code Online (Sandbox Code Playgroud)
这里有一个更有效的方法。
# 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"
Run Code Online (Sandbox Code Playgroud)
reverse_colour意味着您反转刚刚选择的颜色,但处于突出显示模式(默认为白色)。
pink_back(green_back等等......那些有背面的)意味着它以粉红色突出显示(基于名称)。
reset_colour重置颜色(有关更多详细信息,请参见图 1)。
我相信我不需要解释太多,因为它已在变量名称中列出。
如果您想尝试代码,请前往replit IDE测试代码。示例代码在这里
代码(图1):
输出(图2):
这里是一个快速类,它包装了打印功能,可以快速添加颜色,而无需安装额外的包。
(请参阅底部的 2 行解决方案或 1 行解决方案;)这是一个内容丰富且不太冗长的版本
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)
Run Code Online (Sandbox Code Playgroud)
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")
Run Code Online (Sandbox Code Playgroud)
添加它会很有帮助,特别是在脚本编写中(即在脚本末尾添加它),这是因为,在脚本上,上述解决方案可能过于冗长,而您真正想要关注的是脚本编写本身。当然,安装一个像这样的库colorama或使用这个小技巧代替
更具可读性,(随便echo你怎么称呼)
DEFAULT = '\033[0m'; 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';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[97m' # noqa
echo = lambda values, color: print("%s%s%s" % (color, values, DEFAULT)) if color else print("%s%s" % (values, DEFAULT))
echo("This is red", color=RED)
echo("This is green", color=GREEN)
echo("This is cyan", color=CYAN)
Run Code Online (Sandbox Code Playgroud)
只需复制粘贴这一行代码,然后开始使用echo您喜欢的颜色功能
DEFAULT = '\033[0m'; 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';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[97m';echo = lambda values, color: print("%s%s%s" % (color, values, DEFAULT)) if color else print("%s%s" % (values, DEFAULT)) # noqa
echo("This is red", color=RED)
echo("This is green", color=GREEN)
echo("This is cyan", color=CYAN)
Run Code Online (Sandbox Code Playgroud)
小智 7
我建议使用这个新库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")
Run Code Online (Sandbox Code Playgroud)
这是我的现代 (2021) 解决方案:yachalk
它是为数不多的正确支持嵌套样式的库之一:
除此之外,yachalk 是自动完成友好的,支持 256/真彩色,带有终端功能检测,并且是全类型的。
以下是您在选择解决方案时可能会考虑的一些设计决策。
这个问题的许多答案演示了如何直接使用 ANSI 转义码,或建议需要手动启用/禁用样式的低级库。
这些方法有一些微妙的问题:手动插入开/关样式是
因此,如果目标是与许多终端兼容,最好使用提供自动处理样式重置的高级库。这允许库通过在需要的地方插入“虚假”ANSI 转义码来处理所有边缘情况。
在 JavaScript 中,任务的事实上的标准库是chalk,在 JS 项目中使用它一段时间后,Python 世界中可用的解决方案相比之下缺乏。chalk API 不仅使用起来更方便(完全自动完成兼容),它还可以正确处理所有边缘情况。
yachalk的想法是为 Python 生态系统带来同样的便利。如果您对与其他库的比较感兴趣,我已经开始在项目页面上进行功能比较。此外,这里有一个很长的(但仍然不完整的)我在研究期间提出的替代方案列表——有很多可供选择:)
您的终端很可能使用 Unicode(通常为 UTF-8 编码)字符,因此只需选择适当的字体即可查看您喜欢的字符。Unicode char 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()
Run Code Online (Sandbox Code Playgroud)
稍后使用您最喜欢的查看器检查文件。
我创建了一个项目 ( console-color) 并已将其发布到PyPI。
你可以扔 pip install console-color来安装它。
我用 Sphinx-read-the-doc 编写文档,见这里。
您可以从google-colab获得更多示例。
我还是贴了一些例子来吸引用户点击上面的链接:
# 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)
Run Code Online (Sandbox Code Playgroud)
当然,您不必输入所有参数。您只需添加所需的属性即可。
说实话,这个项目并不特别。它只是使用f"\033[{target};2;{r};{g};{b}m{text}{style}"
where 目标是 38 或 48,文本是你的输入字符串,样式是 '\33[0m', '\33[1m' ... '\033[9m'。某种东西。
我只是让它易于使用(至少对我而言)。
作为 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))
Run Code Online (Sandbox Code Playgroud)
PS:受到CircuitSacul的回答的强烈启发
小智 5
使用pyfancy。这是在终端中进行颜色的简单方法!
例子:
print(pyfancy.RED + "Hello Red" + pyfancy.END)
Run Code Online (Sandbox Code Playgroud)
我是 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
Run Code Online (Sandbox Code Playgroud)
或者就像这样:
# 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')
Run Code Online (Sandbox Code Playgroud)
当我在寻找如何为日志着色时,我被谷歌移到了那里,所以:
pip install coloredlogs
Run Code Online (Sandbox Code Playgroud)
pip install coloredlogs
Run Code Online (Sandbox Code Playgroud)
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')
Run Code Online (Sandbox Code Playgroud)
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')
Run Code Online (Sandbox Code Playgroud)
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')
Run Code Online (Sandbox Code Playgroud)
%(asctime)s- 发出日志记录调用时的时间作为人类可读的字符串%(created)f- 发出记录调用时的浮点数时间%(filename)s- 文件名%(funcName)s- 包含日志记录调用的函数名称%(hostname)s- 系统主机名%(levelname)s- 文本记录级别%(levelno)s- 整数记录级别%(lineno)d- 发出日志记录调用的行号%(message)s- 消息传递到日志记录调用(与 相同%(msg)s)%(module)s- 发出日志记录调用的不带扩展名的文件名%(msecs)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- 系统用户名