【问题标题】:How do I print colored output to the terminal in Python?如何在 Python 中将彩色输出打印到终端?
【发布时间】:2016-05-20 07:03:53
【问题描述】:

是否有 Python 等价于 Perl 的

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


【解决方案1】:

Python termcolor module 会这样做吗?这对于某些用途来说是一个粗略的等价物。

from termcolor import colored

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

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

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="")。剩下的工作就是将其打包以供模块化使用(并且更容易消化)。

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

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

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 模块中可用,并且对 order 和类似内容也很敏感。)


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

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

【讨论】:

  • "您也可以像在 Perl 示例中一样使用它——设置颜色(它将 ANSI 转义序列打印到终端),以便所有后续打印都以这种方式进行,直到更改/重启。”能给个示例代码吗?
  • @TurboSullivan 我相信我记得这样的用法,但现在想不起来了。我明天会调查它(这里非常晚了)并回复/发布。顺便说一句,这种用法很简单——您需要做的就是打印颜色和属性的 ANSI,然后其他一切都这样。所以你可以设置它们,只需print RED 左右,所有的打印都是红色的。将这些 ANSI 序列打印到终端进行设置,以便它使用该样式,直到更改。但我会寻找一个现成的方法。
  • @TurboSullivan 到目前为止,我无法找到该模块将如何提供您想要的行为(但我可以发誓它可以完成)。当我在寻找如何做到这一点时,我在帖子中添加了一种通过基本代码打印来做到这一点的方法,包装在一个模块中以供正常(很好)使用。请让我知道这对您有何帮助。
  • &gt;&gt;&gt; sys.stdout.write("\033[1;31m") [1;31m&gt;&gt;&gt; print "All following prints will be red ..." All following prints will be red ... &gt;&gt;&gt; 是我从import sys sys.stdout.write("\033[1;31m") print "All following prints will be red ..." 得到的。没有颜色...
  • @beepbeep-boop 或者你可以用你需要的混合样式组成整行,比如print("first\033[;1m bold\033[1;32m then green");但是最好设置和使用常量print("first " + BOLD + "bold " + GREEN + "then green" + RESET),我已经在其中输入了RESET,这样它就不会在此之后继续打印绿色。
【解决方案2】:

我建议sty。它类似于 colorama,但不那么冗长,它支持 8bit24bit 颜色。您还可以使用自己的颜色扩展颜色寄存器。

示例:

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

演示:

【讨论】:

    【解决方案3】:

    你可以用 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'))
    

    希望对您有所帮助。

    【讨论】:

      【解决方案4】:

      相比这里列出的方法,我更喜欢系统自带的方法。 在这里,我提供一种更好的方法,无需第三方库。

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

      更多颜色代码,参考:Printing Colored Text in Python

      尽情享受吧!

      【讨论】:

      • 确实稍微好一点,因为我们继续支持 print() 的打包 *args 语法,就像在 print(colors.RED, "property:" , value, colors.ENDC)
      【解决方案5】:

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

      【讨论】:

        【解决方案6】:

        这里有一些库可以提供帮助。对于 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 并且易于使用。

        关于此主题和跨平台支持的其他主题:e.g. here

        【讨论】:

        • 示例代码返回错误UnboundLocalError: local variable 'style' referenced before assignment。最终使用了易于使用的 termcolor 库。
        • 抱歉,只是复制和粘贴错误,因为我删除了示例不需要的内容。示例现已修复。
        【解决方案7】:

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

        【讨论】:

          【解决方案8】:

          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/了解更多信息。

          【讨论】:

            猜你喜欢
            • 2010-09-22
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2019-12-09
            • 2011-02-06
            • 1970-01-01
            相关资源
            最近更新 更多