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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37340049/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 19:15:08  来源:igfitidea点击:

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

python

提问by Turbo Sullivan

Is there any python equivalent for perl's

是否有与 perl 等效的 python

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

available in python?

在python中可用?

I knew solution;

我知道解决方案;

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

what I want is I should be able to set color for all print messages like,

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

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

Here 'function_print_something' is my python function which will print some formatted log messages on to the screen.

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

回答by zdim

Would the Python termcolor moduledo? This would be a rough equivalent for some uses.

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

from termcolor import colored

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

The example is right from this post, which has a lot more. Here is a part of the example from docs

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

import sys
from termcolor import colored, cprint

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

A specific requirement was to set the color, and presumably other terminal attributes, so that all following prints are that way. While I stated in the original post that this is possible with this module I now don't think so.See the last section for a way to do that.

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

However, most of the time we print short segments of text in color, a line or two. So the interface in these examples may be a better fit than to 'turn on' a color, print, and then turn it off. (Like in the Perl example shown.) Perhaphs you can add optional argument(s) to your print function for coloring the output as well, and in the function use module's functions to color the text. This also makes it easier to resolve occasional conflicts between formatting and coloring. Just a thought.

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



Here is a basic approach to set the terminal so that all following prints are rendered with a given color, attributes, or mode.

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

Once an appropriate ANSI sequence is sent to the terminal, all following text is rendered that way. Thus if we want all text printed to this terminal in the future to be bright/bold red, print ESC[followed by the codes for "bright" attribute (1) and red color (31), followed by m

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

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

To turn off any previously set attributes use 0 for attribute, \033[0;35m(magenta).

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

To suppress a new line in python 3 use print('...', end=""). The rest of the job is about packaging this for modular use (and for easier digestion).

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

File colors.py

文件颜色.py

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

I recommend a quick read through some references on codes. Colors and attributes can be combined and one can put together a nice list in this package. A script

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

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."

If the constant use of sys.stdout.write()is a bother it can be be wrapped in a tiny function, or the package turned into a class with methods that set terminal behavior (print ANSI codes).

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

Some of the above is more of a suggestion to look it up, like combining reverse mode and color. (This is available in the Perl module used in the question, and is also sensitive to order and similar.)

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



A convenient list of escape codes is surprisingly hard to find, while there are many references on terminal behavior and how to control it. The Wiki page on ANSI escape codeshas all information but requires a little work to bring it together. Pages on Bash prompthave a lot of specific useful information. Here is another pagewith straight tables of codes. There is much more out there.

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

This can be used alongside a module like termocolor.

这可以与像termocolor.

回答by Rotareti

I suggest sty. It's similar to colorama, but less verbose and it supports 8bitand 24bitcolors. You can also extend the color register with your own colors.

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

Examples:

例子:

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

enter image description here

在此处输入图片说明

Demo:

演示:

enter image description here

在此处输入图片说明

回答by Zarif

You can try this with python 3:

你可以用 python 3 试试这个:

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

If you are using windows operating system, the above code may not work for you. Then you can try this code:

如果您使用的是 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'))

Hope that helps.

希望有帮助。

回答by Daniel

There are a few libraries that help out here. For cmdline tools I sometimes use colorama.

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

e.g.

例如

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

But instead of using strings, you might want to use an enum and/or add a few checks. Not the prettiest solution, but works on osx/linux and windows and is easy to use.

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

Other threads about this topic and cross-platform support: e.g. here.

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

回答by Yuhao

What about the ansicolorslibrary? You can simple do:

怎么样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'))

回答by Pervez

Color_Console library is comparatively easier to use. Install this library and the following code would help you.

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.

The latest version of Color_Console allows you to pass a list or dictionary of colors which would change after a specified delay time.

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

Also, they have good documentation on all of their functions.

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

Visit https://pypi.org/project/Color-Console/to know more.

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

回答by Dersu Giritlio?lu

A side note: Windows users should run os.system('color')first, otherwise you would see some ANSI escape sequences rather than a colored output.

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