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

时间:2021-05-18 18:13:55

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函数,它会将一些格式化的日志消息打印到屏幕上。

4 个解决方案

#1


53  

Would the Python termcolor module do? 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

这个例子正好来自这篇文章,其中还有很多内容。以下是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示例中所示。)Perhaphs你可以在打印函数中添加可选参数以便为输出着色,并在函数中使用模块的函数为文本着色。这也可以更容易地解决格式化和着色之间的偶然冲突。只是一个想法。


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

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

文件colors.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"

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 codes has all information but requires a little work to bring it together. Pages on Bash prompt have a lot of specific useful information. Here is another page with straight tables of codes. There is much more out there.

一个方便的转义码列表令人惊讶地难以找到,而有很多关于终端行为以及如何控制它的参考。 ANSI转义码的Wiki页面包含所有信息,但需要一些工作才能将它们组合在一起。 Bash提示页面上有很多特定的有用信息。这是另一个带有直接代码表的页面。还有更多。

This can be used alongside a module like termocolor.

这可以与termocolor等模块一起使用。

#2


6  

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

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

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 new colors:

fg.orange = ('rgb', (255, 150, 50))

buf = fg.orange + 'Yay, Im orange.' + fg.rs


print(foo, bar, baz, qux, qui, buf, sep='\n')

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

Demo:

演示:

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

#3


3  

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.

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

#4


0  

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.

希望有所帮助。

#1


53  

Would the Python termcolor module do? 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

这个例子正好来自这篇文章,其中还有很多内容。以下是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示例中所示。)Perhaphs你可以在打印函数中添加可选参数以便为输出着色,并在函数中使用模块的函数为文本着色。这也可以更容易地解决格式化和着色之间的偶然冲突。只是一个想法。


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

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

文件colors.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"

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 codes has all information but requires a little work to bring it together. Pages on Bash prompt have a lot of specific useful information. Here is another page with straight tables of codes. There is much more out there.

一个方便的转义码列表令人惊讶地难以找到,而有很多关于终端行为以及如何控制它的参考。 ANSI转义码的Wiki页面包含所有信息,但需要一些工作才能将它们组合在一起。 Bash提示页面上有很多特定的有用信息。这是另一个带有直接代码表的页面。还有更多。

This can be used alongside a module like termocolor.

这可以与termocolor等模块一起使用。

#2


6  

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

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

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 new colors:

fg.orange = ('rgb', (255, 150, 50))

buf = fg.orange + 'Yay, Im orange.' + fg.rs


print(foo, bar, baz, qux, qui, buf, sep='\n')

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

Demo:

演示:

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

#3


3  

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.

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

#4


0  

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.

希望有所帮助。