如何在Python中将彩色文本输出到终端?
当前回答
Rich是一个相对较新的Python库,用于在终端中处理颜色。
在Rich中有几种处理颜色的方法。最快的入门方法是富打印方法,它将类似BBCode的语法呈现到ANSI控制代码中:
from rich import print
print("[red]Color[/] in the [bold magenta]Terminal[/]!")
还有其他方法可以通过Rich(正则表达式、语法)和相关的格式化功能应用颜色。
其他回答
使用pyfancy。这是一种在终端中进行颜色处理的简单方法!
例子:
print(pyfancy.RED + "Hello Red" + pyfancy.END)
如果您正在使用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'])
它输出“你好,世界!”,单词为蓝色,感叹号为粗体红色并闪烁。
为了解决这个问题,我创建了一个简单得让人麻木的程序包,用插值颜色代码打印字符串,称为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。
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')