繁体   English   中英

如何在 Python 中将彩色输出打印到终端?

[英]How do I print colored output to the terminal in Python?

是否有与 Perl 等效的 Python

print color 'red';
print <something>;
print color 'reset';

可用?

我正在使用这种方法:

"\x1b[1;%dm" % (<color code>) + "ERROR: log file does not exist" + "\x1b[0m"

我想要的是我应该能够为所有打印消息设置颜色,例如,

print color 'red'
function_print_something(<some message>)
print color 'reset'

这里'function_print_something'是我的python函数,它将在屏幕上打印一些格式化的日志消息。

Python termcolor 模块可以吗? 对于某些用途,这将是一个粗略的等价物。

from termcolor import colored

print colored('hello', 'red'), colored('world', 'green')

这个例子来自这篇文章,还有很多。 这是文档中示例的一部分

import sys
from termcolor import colored, cprint

text = colored('Hello, World!', 'red', attrs=['reverse', 'blink'])
print(text)
cprint('Hello, World!', 'green', 'on_red')

一个特定的要求是设置颜色,可能还有其他终端属性,以便接下来的所有打印都是这样。 虽然我在最初的帖子中说这个模块可以做到这一点,但我现在不这么认为。 请参阅最后一节以了解如何做到这一点。

但是,大多数情况下,我们会打印一小段彩色文本,一两行。 因此,这些示例中的界面可能比“打开”颜色、打印然后关闭它更适合。 (就像显示的 Perl 示例一样。)也许您可以将可选参数添加到打印函数中以对输出进行着色,并在该函数中使用模块的函数为文本着色。 这也可以更轻松地解决格式和着色之间的偶然冲突。 只是一个想法。


这是设置终端的基本方法,以便使用给定的颜色、属性或模式呈现所有后续打印。

一旦将适当的 ANSI 序列发送到终端,接下来的所有文本都会以这种方式呈现。 因此,如果我们希望将来打印到此终端的所有文本都是亮/粗红色,请打印ESC[后跟“明亮”属性 (1) 和红色 (31) 的代码,然后是m

# print "\033[1;31m"   # this would emit a new line as well
import sys
sys.stdout.write("\033[1;31m")
print "All following prints will be red ..."

要关闭任何先前设置的属性,请使用 0 作为属性, \\033[0;35m (洋红色)。

要在 python 3 中取消新行,请使用print('...', end="") 剩下的工作是将其打包以供模块化使用(并且更容易消化)。

文件颜色.py

RED   = "\033[1;31m"  
BLUE  = "\033[1;34m"
CYAN  = "\033[1;36m"
GREEN = "\033[0;32m"
RESET = "\033[0;0m"
BOLD    = "\033[;1m"
REVERSE = "\033[;7m"

我建议快速阅读一些有关代码的参考资料。 颜色和属性可以组合在一起,可以在这个包中组合一个不错的列表。 一个脚本

import sys
from colors import *

sys.stdout.write(RED)
print "All following prints rendered in red, until changed"

sys.stdout.write(REVERSE + CYAN)
print "From now on change to cyan, in reverse mode"
print "NOTE: 'CYAN + REVERSE' wouldn't work"

sys.stdout.write(RESET)
print "'REVERSE' and similar modes need be reset explicitly"
print "For color alone this is not needed; just change to new color"
print "All normal prints after 'RESET' above."

如果经常使用sys.stdout.write()很麻烦,则可以将其包装在一个小函数中,或者将包转换为具有设置终端行为的方法(打印 ANSI 代码)的类。

上面的一些更像是查找它的建议,例如组合反向模式和颜色。 (这在问题中使用的 Perl 模块中可用,并且对顺序和类似也很敏感。)


很难找到方便的转义码列表,但有许多关于终端行为及其控制方法的参考资料。 ANSI 转义码Wiki 页面包含所有信息,但需要做一些工作才能将其整合在一起。 Bash 提示页面有很多特定的有用信息。 这是另一个带有直接代码表的页面 还有更多。

这可以与诸如termocolor类的模块一起使用。

我建议麦粒肿 它类似于 colorama,但不那么冗长,并且支持8 位24 位颜色。 您还可以使用自己的颜色扩展颜色寄存器。

例子:

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')

在此处输入图片说明

演示:

在此处输入图片说明

你可以用 python 3 试试这个:

from termcolor import colored
print(colored('Hello, World!', 'green', 'on_red'))

如果您使用的是 windows 操作系统,上面的代码可能不适合您。 然后你可以试试这个代码:

from colorama import init
from termcolor import colored

# use Colorama to make Termcolor work on Windows too
init()

# then use Termcolor for all colored text output
print(colored('Hello, World!', 'green', 'on_red'))

希望有帮助。

旁注:Windows 用户应该首先运行os.system('color') ,否则你会看到一些 ANSI 转义序列而不是彩色输出。

与这里列出的方法相比,我更喜欢系统自带的方法。 在这里,我提供了一个没有第三方库的更好的方法。

class colors: # You may need to change color settings
    RED = '\033[31m'
    ENDC = '\033[m'
    GREEN = '\033[32m'
    YELLOW = '\033[33m'
    BLUE = '\033[34m'

print(colors.RED + "something you want to print in red color" + colors.ENDC)
print(colors.GREEN + "something you want to print in green color" + colors.ENDC)
print("something you want to print in system default color")

更多颜色代码,请参考: 在 Python 中打印彩色文本

尽情享受吧!

有一些图书馆可以在这里提供帮助。 对于 cmdline 工具,我有时会使用colorama

例如

from colorama import init, Fore, Back, Style
init()

def cprint(msg, foreground = "black", background = "white"):
    fground = foreground.upper()
    bground = background.upper()
    style = getattr(Fore, fground) + getattr(Back, bground)
    print(style + msg + Style.RESET_ALL)

cprint("colorful output, wohoo", "red", "black")

但是,您可能希望使用枚举和/或添加一些检查,而不是使用字符串。 不是最漂亮的解决方案,但适用于 osx/linux 和 windows 并且易于使用。

关于此主题和跨平台支持的其他线程: 例如这里

ansicolors库怎么样? 你可以简单地做:

from colors import color, red, blue

# common colors
print(red('This is red'))
print(blue('This is blue'))

# colors by name or code
print(color('Print colors by name or code', 'white', '#8a2be2'))

Color_Console 库比较容易使用。 安装这个库,下面的代码会对你有所帮助。

from Color_Console import *
ctext("This will be printed" , "white" , "blue")
The first argument is the string to be printed, The second argument is the color of 
the text and the last one is the background color.

最新版本的 Color_Console 允许您传递颜色列表或字典,这些颜色将在指定的延迟时间后发生变化。

此外,他们对所有功能都有很好的文档。

访问https://pypi.org/project/Color-Console/了解更多信息。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM