【问题标题】:How do I print colored text to the terminal?如何将彩色文本打印到终端?
【发布时间】:2008-11-13 18:58:10
【问题描述】:

如何在 Python 中将彩色文本输出到终端?

【问题讨论】:

  • 这个符号将成为一个很棒的彩色块: 唯一的问题是它是扩展的 ASCII,也许你可以使用 http://stackoverflow.com/questions/8465226/using-extended-ascii-codes-with-python 来让它工作
  • 有些终端也可以显示Unicode字符。如果您的终端是这样,那么可能的字符几乎是无限的。
  • 这个答案来得相当晚,但对我来说似乎是最好的......上面投票的那些需要 Windows 的特殊黑客,而这个只是有效:stackoverflow.com/a/3332860/901641
  • stackoverflow.com/a/42528796/610569 使用 pypi.python.org/pypi/lazyme 怎么样? (免责声明:无耻插件)
  • 如果您不想安装额外的软件包,请关注new answer

标签: python terminal output ansi-colors


【解决方案1】:

这在某种程度上取决于您使用的平台。最常见的方法是打印 ANSI 转义序列。举个简单的例子,下面是来自Blender build scripts的一些Python代码:

class bcolors:
    HEADER = '\033[95m'
    OKBLUE = '\033[94m'
    OKCYAN = '\033[96m'
    OKGREEN = '\033[92m'
    WARNING = '\033[93m'
    FAIL = '\033[91m'
    ENDC = '\033[0m'
    BOLD = '\033[1m'
    UNDERLINE = '\033[4m'

要使用这样的代码,您可以执行以下操作:

print(bcolors.WARNING + "Warning: No active frommets remain. Continue?" + bcolors.ENDC)

或者,使用 Python 3.6+:

print(f"{bcolors.WARNING}Warning: No active frommets remain. Continue?{bcolors.ENDC}")

这将适用于包括 OS X、Linux 和 Windows 在内的 unix(前提是您使用 ANSICON,或者在 Windows 10 中启用 VT100 emulation)。有用于设置颜色、移动光标等的 ANSI 代码。

如果您要对此感到复杂(听起来好像您正在编写游戏),您应该查看“curses”模块,它处理了很多复杂的部分你。 Python Curses HowTO 是一个很好的介绍。

如果您不使用扩展 ASCII(即不在 PC 上),您会被 127 以下的 ASCII 字符卡住,而“#”或“@”可能是您最好的选择。如果您可以确保您的终端使用的是 IBM extended ASCII character set,那么您有更多选择。字符 176、177、178 和 219 是“块字符”。

一些现代的基于文本的程序,例如“矮人要塞”,以图形模式模拟文本模式,并使用经典 PC 字体的图像。您可以在Dwarf Fortress Wiki 上找到一些可以使用的位图,请参阅 (user-made tilesets)。

Text Mode Demo Contest 有更多资源用于在文本模式下绘制图形。

【讨论】:

  • 在 Linux 上,您可能希望使用 tputlike so,因为这样会产生更便携的代码。
  • @Cawas:disable 的一个真实用例是将输出通过管道传输到文件;虽然像cat 这样的工具可能支持颜色,但通常最好不要将颜色信息打印到文件中。
  • @AlexanderSimko,这是在 Windows 10 中启用 VT100 支持的 ctypes 代码 sn-p:import ctypes;kernel32 = ctypes.WinDLL('kernel32');hStdOut = kernel32.GetStdHandle(-11);mode = ctypes.c_ulong();kernel32.GetConsoleMode(hStdOut, ctypes.byref(mode));mode.value |= 4;kernel32.SetConsoleMode(hStdOut, mode)。。跨度>
  • 致任何使用 Python 示例代码的人:应该注意,90-97 和 100-107 范围内的颜色是 非标准的,而且确实,在我的终端上,它们并不都给出变量名称所指示的颜色。最好使用标准范围 30-37 和 40-47。来源:en.wikipedia.org/wiki/…
  • A good reference 了解术语颜色的工作原理:jafrog.com/2013/11/23/colors-in-terminal.html
【解决方案2】:

还有Python termcolor module。用法很简单:

from termcolor import colored

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

或者在 Python 3 中:

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

但是,对于游戏编程和您想要做的“彩色块”来说,它可能不够复杂......

要让 ANSI 代码在 Windows 上运行,请先运行

os.system('color')

【讨论】:

  • 由于它发出 ANSI 代码,如果加载了 ansi.sys,它是否可以在 Windows(DOS 控制台)上运行? support.microsoft.com/kb/101875
  • 刚刚注意到,截至 2011 年 1 月 13 日,它现在处于 MIT 许可下
  • 没有单元测试(与 colorama 不同)并且自 2011 年以来未更新
  • termcolor.COLORS 为您提供颜色列表
  • 在 Windows 上首先运行 os.system('color'),然后 ANSI 转义序列开始工作。
【解决方案3】:

答案是Colorama,用于 Python 中的所有跨平台着色。

它支持 Python 3.5+ 以及 Python 2.7。

自 2021 年 1 月起,它得到维护。

示例截图:

【讨论】:

  • 作为Colorama的作者,感谢@nbv4的提及。我将尝试澄清一下:Colorama 旨在让 Python 程序在所有平台上打印彩色终端文本,使用与本页许多其他答案中描述的相同的 ANSI 代码。在 Windows 上,Colorama 从标准输出中去除这些 ANSI 字符,并将它们转换为对彩色文本的等效 win32 调用。在其他平台上,Colorama 什么都不做。因此,您可以使用 ANSI 代码或 Termcolor 之类的模块,并且使用 Colorama,它们在所有平台上都“正常工作”。无论如何,这是不是这个想法。
  • @Jonathan,这真是一个很棒的图书馆!跨平台彩色 Python 输出的能力真的非常好和有用。我正在为一个为自己的控制台着色的库提供工具。我可以将该控制台的输出重定向到终端并对输出进行着色。现在我什至可以创建一个库并让用户选择颜色。这将允许色盲者设置工作,以便他们可以正确地看到输出。谢谢
  • 这应该在标准库中...我认为跨平台颜色支持很重要。
  • Colorama 很棒!还可以查看 ansimarkup,它基于 colorama 构建,允许您使用简单的基于标签的标记(例如 <b>bold</b>)为终端文本添加样式
  • 如果不调用 colorama.init(),这将不起作用。投票!
【解决方案4】:

打印一个以颜色/样式开头的字符串,然后是字符串,然后以'\x1b[0m'结束颜色/样式更改:

print('\x1b[6;30;42m' + 'Success!' + '\x1b[0m')

使用以下代码获取 shell 文本的格式选项表:

def print_format_table():
    """
    prints table of formatted text format options
    """
    for style in range(8):
        for fg in range(30,38):
            s1 = ''
            for bg in range(40,48):
                format = ';'.join([str(style), str(fg), str(bg)])
                s1 += '\x1b[%sm %s \x1b[0m' % (format, format)
            print(s1)
        print('\n')

print_format_table()

明暗示例(完整)

暗光示例(部分)

参考:https://en.wikipedia.org/wiki/ANSI_escape_code#Colors

【讨论】:

  • 这适用于大多数 shell 以及 ipython,对于大多数应用程序来说足够好
  • 请问,这是哪个终端?
  • 便携性如何?
  • 要在 Windows 10 Powershell 中进行这项工作,请在 Python 中导入 os,然后执行 os.system('color')。从那时起,ANSI 转义序列将神奇地起作用。
【解决方案5】:

在我看来,这是最简单的方法。只要你有你想要的颜色的 RGB 值,这应该可以工作:

def colored(r, g, b, text):
    return f"\033[38;2;{r};{g};{b}m{text}\033[38;2;255;255;255m"

打印红色文字的例子:

text = 'Hello, World!'
colored_text = colored(255, 0, 0, text)
print(colored_text)

#or

print(colored(255, 0, 0, 'Hello, World!'))

多色文字

text = colored(255, 0, 0, 'Hello, ') + colored(0, 255, 0, 'World')
print(text)

【讨论】:

  • 这实际上是问题的正确答案,应该选择。问题是如何在 python 中打印颜色,而不是可以使用哪些外部库。
  • @mike_rodent 这不是 *nix 特定的,但取决于终端是否支持 ANSI
  • 这可以使用 lambda 和 f 字符串进一步整理:`colored = lambda r, g, b, text: f'\033[38;2;{r};{g}; {b}m{文本} \033[38;2;255;255;255m'
  • 当前实现后有一个副作用尾随空格。您可以通过从字符串格式中删除尾随空格来摆脱。改用这个:f"\033[38;2;{r};{g};{b}m{text}\033[38;2;255;255;255m"
  • @Elyasaf755 谢谢,已修复。
【解决方案6】:

定义一个开始颜色的字符串和结束颜色的字符串。然后打印你的文本,开始字符串在前面,结束字符串在结尾。

CRED = '\033[91m'
CEND = '\033[0m'
print(CRED + "Error, does not compute!" + CEND)

这会在 Bash 中使用 Zenburn 风格的配色方案在 urxvt 中生成以下内容:

通过实验,我们可以得到更多的颜色:

注意:\33[5m\33[6m 正在闪烁。

这样我们可以创建一个完整的颜色集合:

CEND      = '\33[0m'
CBOLD     = '\33[1m'
CITALIC   = '\33[3m'
CURL      = '\33[4m'
CBLINK    = '\33[5m'
CBLINK2   = '\33[6m'
CSELECTED = '\33[7m'

CBLACK  = '\33[30m'
CRED    = '\33[31m'
CGREEN  = '\33[32m'
CYELLOW = '\33[33m'
CBLUE   = '\33[34m'
CVIOLET = '\33[35m'
CBEIGE  = '\33[36m'
CWHITE  = '\33[37m'

CBLACKBG  = '\33[40m'
CREDBG    = '\33[41m'
CGREENBG  = '\33[42m'
CYELLOWBG = '\33[43m'
CBLUEBG   = '\33[44m'
CVIOLETBG = '\33[45m'
CBEIGEBG  = '\33[46m'
CWHITEBG  = '\33[47m'

CGREY    = '\33[90m'
CRED2    = '\33[91m'
CGREEN2  = '\33[92m'
CYELLOW2 = '\33[93m'
CBLUE2   = '\33[94m'
CVIOLET2 = '\33[95m'
CBEIGE2  = '\33[96m'
CWHITE2  = '\33[97m'

CGREYBG    = '\33[100m'
CREDBG2    = '\33[101m'
CGREENBG2  = '\33[102m'
CYELLOWBG2 = '\33[103m'
CBLUEBG2   = '\33[104m'
CVIOLETBG2 = '\33[105m'
CBEIGEBG2  = '\33[106m'
CWHITEBG2  = '\33[107m'

这是生成测试的代码:

x = 0
for i in range(24):
  colors = ""
  for j in range(5):
    code = str(x+j)
    colors = colors + "\33[" + code + "m\\33[" + code + "m\033[0m "
  print(colors)
  x = x + 5

【讨论】:

  • 什么外壳或终端让它闪烁?
  • (u)rxvt 例如
  • 仅供参考 - 上面标记为“米色”的是 Apple 终端上的浅青色(以及 Python 的许多其他颜色名称列表)。此外,一些双色是浅色/深色版本,白色变体我称之为白色和灰色......
  • @captain \33[25m 也应该表示“不闪烁”,无需重置其他样式 - en.wikipedia.org/wiki/…
【解决方案7】:

这是一个在 Windows 10 上原生运行的解决方案。

使用系统调用,例如os.system(""),允许在命令提示符和 Powershell 中本地打印颜色:

import os

# System call
os.system("")

# Class of different styles
class style():
    BLACK = '\033[30m'
    RED = '\033[31m'
    GREEN = '\033[32m'
    YELLOW = '\033[33m'
    BLUE = '\033[34m'
    MAGENTA = '\033[35m'
    CYAN = '\033[36m'
    WHITE = '\033[37m'
    UNDERLINE = '\033[4m'
    RESET = '\033[0m'

print(style.YELLOW + "Hello, World!")

注意:Windows 不完全支持 ANSI 代码,无论是通过系统调用还是模块。并非所有文本装饰都受支持,虽然显示的是亮色,但它们与常规颜色相同。

感谢@j-l 找到更短的方法。

tl;dr:添加os.system("")

【讨论】:

  • 这行得通 - 我真的很惊讶 color 命令在 Windows 终端中启用了 ANSI 代码,我已经走了很多年而不知道这是可能的 - 命令本身并没有给出任何线索它会这样做。
  • 非常感谢您的回答,@SimpleBinary!玩弄您的答案,我发现您可以进一步简化if sys.platform.lower() == "win32": os.system('color'),只需将其替换为os.system('')。不需要条件,代码在 Windows 10 和 Linux 中都可以运行(当我测试它时)。如您所见,您不必对color 进行系统调用。对dircdabcdef 的调用以及空字符串都可以正常工作(尽管非空字符串可能会打印您不想看到的输出)。
  • 简而言之,对color 的调用不是关键部分;在 Windows 10 上运行时,正是 os.system(command) 行本身使打印颜色成为可能。“命令”可以是任何东西,真的 - 甚至只是一个空字符串。
  • 这真的很有趣!为什么os.system("") 会导致颜色代码起作用?
  • @Starwarswii 这不是 python 的实现,在调用 system(""); (include <stdlib.h>) 之后在 Windows 中运行 printf(fmt, ...); 并使用 ASNI 代码打印彩色文本,我仍然很好奇为什么会这样?
【解决方案8】:

Rich 是一个相对较新的 Python 库,用于在终端中处理颜色。

在 Rich 中有几种处理颜色的方法。最快的入门方法是丰富的打印方法,它将类似BBCode 的语法呈现到 ANSI 控制代码中:

from rich import print
print("[red]Color[/] in the [bold magenta]Terminal[/]!")

还有其他方法可以通过 Rich(正则表达式、语法)和相关格式功能应用颜色。

【讨论】:

    【解决方案9】:

    这是我的现代 (2021) 解决方案:yachalk

    它是少数几个正确支持嵌套样式的库之一:

    除此之外,yachalk 支持自动完成,支持 256/真彩色,带有终端功能检测,并且是全类型化的。

    以下是您在选择解决方案时可能会考虑的一些设计决策。

    高级库与低级库/手动样式处理?

    这个问题的许多答案演示了如何直接转义 ANSI 代码,或建议需要手动启用/禁用样式的低级库。

    这些方法有一些微妙的问题:手动插入开/关样式是

    • 在语法上更详细,因为必须明确指定重置,
    • 更容易出错,因为您可能会不小心忘记重置样式,
    • 无法正确处理边缘情况:例如,在某些终端中,需要在换行符之前重置样式,并在换行符后重新激活它们。此外,某些终端在简单地覆盖互斥样式方面存在问题,并且需要插入“不必要的”重置代码。如果开发者的本地终端没有这些怪癖,开发者不会立即发现这些怪癖。该问题只会由其他人稍后报告或导致问题,例如在 CI 终端上。

    因此,如果与许多终端兼容是一个目标,最好使用提供自动处理样式重置的高级库。这允许库通过在需要的地方插入“虚假”ANSI 转义码来处理所有边缘情况。

    为什么还要另一个库?

    在 JavaScript 中,该任务的事实上的标准库是 chalk,在 JS 项目中使用了一段时间后,相比之下,Python 世界中可用的解决方案是缺乏的。 chalk API 不仅使用起来更方便(完全兼容自动完成),而且还能正确处理所有边缘情况。

    yachalk 的想法是为 Python 生态系统带来同样的便利。如果您对与其他库的比较感兴趣,我已经在项目页面上开始 feature comparison。此外,这里有一个很长(但仍然不完整)的替代方案列表,这些替代方案在我的研究过程中出现——有很多可供选择:)

    【讨论】:

    【解决方案10】:

    sty与colorama类似,但不那么冗长,支持8-bit24-bit(RGB)颜色,支持所有effects(粗体、下划线等),允许你register your own styles,完全类型化且高性能,支持muting,不会与sys.stdout 等全局变量混淆,非常灵活,documented 等等...

    示例:

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

    打印:

    演示:

    【讨论】:

    • 如果您考虑将它与 colorama 进行比较,这将非常有用,我更喜欢您的库,但这只是因为盒子里的 api 更短,如果它更受欢迎那就太好了。谢谢!
    • 我喜欢 sty,我正在尝试用 sty 格式化我的字符串,一个问题是,当我打印多种颜色时,我可以重置为以前的颜色而不是默认颜色吗?
    • @VictorGavro 这是个好主意!我可能会在文档中添加一个比较。
    • @intijk 您的问题并不适合评论部分。对于此类问题,请创建一个新的 SO Question 或使用 github issue tracker。
    • @intijk :使用代码 fg.rsbg.rs 分别将前景色和背景色重置为默认值。
    【解决方案11】:

    您想了解 ANSI 转义序列。这是一个简短的例子:

    CSI = "\x1B["
    print(CSI+"31;40m" + "Colored Text" + CSI + "0m")
    

    有关详细信息,请参阅 ANSI escape code

    对于块字符,尝试使用 Unicode 字符,如 \u2588:

    print(u"\u2588")
    

    把它们放在一起:

    print(CSI+"31;40m" + u"\u2588" + CSI + "0m")
    

    【讨论】:

    • 尝试def d(*v): return '\x1B['+';'.join(map(str, v))+'m' 然后print ' '.join([d(k,i)+str(i%10)+d(0) for i in range(30,38)+range(40,48) for k in range(2)])
    • 这里的reset是什么意思?
    • 我一直在尝试这个解决方案。 "31;40m" "0m"的目的是什么?
    • @Qohelet:您是否点击了“ANSI 转义码”的链接?它解释了 ANSI 转义序列是如何工作的。第一组数字告诉终端开始使用特定的前景色和背景色,0m 告诉终端停止使用该颜色。
    • @BryanOakley - 我想知道这没有发生。 Python3.7 将其打印为常规文本。
    【解决方案12】:

    我使用for 循环生成了一个包含所有颜色的类,以迭代每个颜色组合,直到 100,然后用 Python 颜色编写了一个类。随意复制粘贴,我的 GPLv2:

    class colors:
        '''Colors class:
        Reset all colors with colors.reset
        Two subclasses fg for foreground and bg for background.
        Use as colors.subclass.colorname.
        i.e. colors.fg.red or colors.bg.green
        Also, the generic bold, disable, underline, reverse, strikethrough,
        and invisible work with the main class
        i.e. colors.bold
        '''
        reset='\033[0m'
        bold='\033[01m'
        disable='\033[02m'
        underline='\033[04m'
        reverse='\033[07m'
        strikethrough='\033[09m'
        invisible='\033[08m'
        class fg:
            black='\033[30m'
            red='\033[31m'
            green='\033[32m'
            orange='\033[33m'
            blue='\033[34m'
            purple='\033[35m'
            cyan='\033[36m'
            lightgrey='\033[37m'
            darkgrey='\033[90m'
            lightred='\033[91m'
            lightgreen='\033[92m'
            yellow='\033[93m'
            lightblue='\033[94m'
            pink='\033[95m'
            lightcyan='\033[96m'
        class bg:
            black='\033[40m'
            red='\033[41m'
            green='\033[42m'
            orange='\033[43m'
            blue='\033[44m'
            purple='\033[45m'
            cyan='\033[46m'
            lightgrey='\033[47m'
    

    【讨论】:

      【解决方案13】:

      windows 10 中,您可以尝试这个小脚本,它用作颜色混合器,红色、绿色和蓝色的值在 0-255 之间:

      import os
      
      os.system('')
      
      
      def RGB(red=None, green=None, blue=None,bg=False):
          if(bg==False and red!=None and green!=None and blue!=None):
              return f'\u001b[38;2;{red};{green};{blue}m'
          elif(bg==True and red!=None and green!=None and blue!=None):
              return f'\u001b[48;2;{red};{green};{blue}m'
          elif(red==None and green==None and blue==None):
              return '\u001b[0m'
      

      并调用 RGB 函数将任意颜色组合为:

      g0 = RGB()
      g1 = RGB(0,255,0)
      g2 = RGB(0,100,0,True)+""+RGB(100,255,100)
      g3 = RGB(0,255,0,True)+""+RGB(0,50,0)
      
      print(f"{g1}green1{g0}")
      print(f"{g2}green2{g0}")
      print(f"{g3}green3{g0}")
      

      RGB() 不带参数将清除并将前景/背景颜色设置为默认。如果您想要 black,则应将其称为 RGB(0,0,0),而对于 white,则应称为 RGB(255,255,255)。而RGB(0,255,0) 会产生绝对绿色RGB(150,255,150) 会产生浅绿色

      这支持 backgroundforeground 颜色,要将颜色设置为 background 颜色,您必须使用 bg=True 传递它,即 @987654329 @ 默认情况下。

      例如:要将 red 设置为 背景色,应将其命名为 RGB(255,0,0,True) 但选择 red 作为 字体颜色只需将其称为RGB(255,0,0,False),因为bg默认为False,这简化了将其称为RGB(255,0,0)

      【讨论】:

      • 每个人都记住这些颜色是terminal independent,这意味着如果你想要某种不是来自终端的TERM 256 colors的绿色,它的going to work
      【解决方案14】:

      对于 Windows,除非您使用 Win32 API,否则您无法使用颜色打印到控制台。

      对于 Linux,它就像使用 print 一样简单,这里列出了转义序列:

      Colors

      要让字符像框一样打印,这实际上取决于您在控制台窗口中使用的字体。磅符号效果很好,但取决于字体:

      #
      

      【讨论】:

      • 在 windows 10 中,如果您在代码开头调用 os.system(''),颜色的工作方式与 linux 类似
      【解决方案15】:

      joeld's answer 为基础,使用https://pypi.python.org/pypi/lazyme
      pip install -U lazyme

      from lazyme.string import color_print
      >>> color_print('abc')
      abc
      >>> color_print('abc', color='pink')
      abc
      >>> color_print('abc', color='red')
      abc
      >>> color_print('abc', color='yellow')
      abc
      >>> color_print('abc', color='green')
      abc
      >>> color_print('abc', color='blue', underline=True)
      abc
      >>> color_print('abc', color='blue', underline=True, bold=True)
      abc
      >>> color_print('abc', color='pink', underline=True, bold=True)
      abc
      

      截图:


      使用新格式化程序对color_print 进行了一些更新,例如:

      >>> from lazyme.string import palette, highlighter, formatter
      >>> from lazyme.string import color_print
      >>> palette.keys() # Available colors.
      ['pink', 'yellow', 'cyan', 'magenta', 'blue', 'gray', 'default', 'black', 'green', 'white', 'red']
      >>> highlighter.keys() # Available highlights.
      ['blue', 'pink', 'gray', 'black', 'yellow', 'cyan', 'green', 'magenta', 'white', 'red']
      >>> formatter.keys() # Available formatter,
      ['hide', 'bold', 'italic', 'default', 'fast_blinking', 'faint', 'strikethrough', 'underline', 'blinking', 'reverse']
      

      注意:italicfast blinkingstrikethrough 可能无法在所有终端上运行,并且它们不适用于 Mac 和 Ubuntu。

      例如,

      >>> color_print('foo bar', color='pink', highlight='white')
      foo bar
      >>> color_print('foo bar', color='pink', highlight='white', reverse=True)
      foo bar
      >>> color_print('foo bar', color='pink', highlight='white', bold=True)
      foo bar
      >>> color_print('foo bar', color='pink', highlight='white', faint=True)
      foo bar
      >>> color_print('foo bar', color='pink', highlight='white', faint=True, reverse=True)
      foo bar
      >>> color_print('foo bar', color='pink', highlight='white', underline=True, reverse=True)
      foo bar
      

      截图:

      【讨论】:

        【解决方案16】:
        def black(text):
            print('\033[30m', text, '\033[0m', sep='')
        
        def red(text):
            print('\033[31m', text, '\033[0m', sep='')
        
        def green(text):
            print('\033[32m', text, '\033[0m', sep='')
        
        def yellow(text):
            print('\033[33m', text, '\033[0m', sep='')
        
        def blue(text):
            print('\033[34m', text, '\033[0m', sep='')
        
        def magenta(text):
            print('\033[35m', text, '\033[0m', sep='')
        
        def cyan(text):
            print('\033[36m', text, '\033[0m', sep='')
        
        def gray(text):
            print('\033[90m', text, '\033[0m', sep='')
        
        
        black("BLACK")
        red("RED")
        green("GREEN")
        yellow("YELLOW")
        blue("BLACK")
        magenta("MAGENTA")
        cyan("CYAN")
        gray("GRAY")
        

        Try online

        【讨论】:

        • 这仅适用于 python3 吗?使用 python2 在 sep='' 上出现错误
        • 这应该是python3的公认答案。完美运行。
        【解决方案17】:

        我最终这样做了,我觉得它最干净:

        formatters = {
            'RED': '\033[91m',
            'GREEN': '\033[92m',
            'END': '\033[0m',
        }
        
        print 'Master is currently {RED}red{END}!'.format(**formatters)
        print 'Help make master {GREEN}green{END} again!'.format(**formatters)
        

        【讨论】:

        • 这对于在没有第三方软件包的情况下进行操作非常好。
        【解决方案18】:

        当我在寻找如何为日志着色时,我被谷歌搬到了那里:

        彩色日志

        安装

        pip install coloredlogs
        

        用法

        最少使用:
        import logging
        import coloredlogs
        
        coloredlogs.install()  # install a handler on the root logger
        
        logging.debug('message with level debug')
        logging.info('message with level info')
        logging.warning('message with level warning')
        logging.error('message with level error')
        logging.critical('message with level critical')
        

        结果:

        从消息级调试开始:
        import logging
        import coloredlogs
        
        coloredlogs.install(level='DEBUG')  # install a handler on the root logger with level debug
        
        logging.debug('message with level debug')
        logging.info('message with level info')
        logging.warning('message with level warning')
        logging.error('message with level error')
        logging.critical('message with level critical')
        

        结果:

        隐藏库中的消息:
        import logging
        import coloredlogs
        
        logger = logging.getLogger(__name__)  # get a specific logger object
        coloredlogs.install(level='DEBUG')  # install a handler on the root logger with level debug
        coloredlogs.install(level='DEBUG', logger=logger)  # pass a specific logger object
        
        logging.debug('message with level debug')
        logging.info('message with level info')
        logging.warning('message with level warning')
        logging.error('message with level error')
        logging.critical('message with level critical')
        

        结果:

        格式化日志消息:
        import logging
        import coloredlogs
        
        logger = logging.getLogger(__name__)  # get a specific logger object
        coloredlogs.install(level='DEBUG')  # install a handler on the root logger with level debug
        coloredlogs.install(level='DEBUG', logger=logger)  # pass a specific logger object
        coloredlogs.install(
            level='DEBUG', logger=logger,
            fmt='%(asctime)s.%(msecs)03d %(filename)s:%(lineno)d %(levelname)s %(message)s'
        )
        
        logging.debug('message with level debug')
        logging.info('message with level info')
        logging.warning('message with level warning')
        logging.error('message with level error')
        logging.critical('message with level critical')
        

        结果:

        可用的格式属性:
        • %(asctime)s - 发出记录调用时作为人类可读字符串的时间
        • %(created)f - 发出记录调用时的浮点时间
        • %(filename)s - 文件名
        • %(funcName)s - 包含日志调用的函数名称
        • %(hostname)s - 系统主机名
        • %(levelname)s - 文本记录级别
        • %(levelno)s - 整数日志记录级别
        • %(lineno)d - 发出记录调用的行号
        • %(message)s - 传递给日志调用的消息(与 %(msg)s 相同)
        • %(module)s - 发出日志调用的文件名不带扩展名
        • %(msecs)d - 发出记录调用时的毫秒部分
        • %(msg)s - 消息传递给日志调用(与 %(message)s 相同)
        • %(name)s - 记录器名称
        • %(pathname)s - 包含日志调用的文件的完整路径名
        • %(process)d - 进程 ID
        • %(processName)s - 进程名称
        • %(programname)s - 系统程序名
        • %(relativeCreated)d - 发出记录调用时的整数毫秒数,相对于加载记录模块的时间
        • %(thread)d - 线程 ID
        • %(threadName)s - 线程名称
        • %(username)s - 系统用户名

        来源:

        Coloredlogs package

        Logging library

        【讨论】:

          【解决方案19】:

          在 Windows 上,您可以使用模块“win32console”(在某些 Python 发行版中可用)或模块“ctypes”(Python 2.5 及更高版本)来访问 Win32 API。

          要查看支持这两种方式的完整代码,请参阅Testoob 中的color console reporting code

          ctypes 示例:

          import ctypes
          
          # Constants from the Windows API
          STD_OUTPUT_HANDLE = -11
          FOREGROUND_RED    = 0x0004 # text color contains red.
          
          def get_csbi_attributes(handle):
              # Based on IPython's winconsole.py, written by Alexander Belchenko
              import struct
              csbi = ctypes.create_string_buffer(22)
              res = ctypes.windll.kernel32.GetConsoleScreenBufferInfo(handle, csbi)
              assert res
          
              (bufx, bufy, curx, cury, wattr,
              left, top, right, bottom, maxx, maxy) = struct.unpack("hhhhHhhhhhh", csbi.raw)
              return wattr
          
          
          handle = ctypes.windll.kernel32.GetStdHandle(STD_OUTPUT_HANDLE)
          reset = get_csbi_attributes(handle)
          
          ctypes.windll.kernel32.SetConsoleTextAttribute(handle, FOREGROUND_RED)
          print "Cherry on top"
          ctypes.windll.kernel32.SetConsoleTextAttribute(handle, reset)
          

          【讨论】:

          • 老实说,这是唯一适用于 Windows 的解决方案。所有其他答案只是彼此的副本。
          • FWIW,在 Windows 上使用支持 ANSI 序列的 ConEmu 可能不会那么痛苦(除了与本机终端相比的许多其他优势)。不过,拥有原生解决方案仍然很棒。
          • 我和达尼洛在一起。
          • @Danilo 注意到这个答案:stackoverflow.com/a/3332860/12291742
          【解决方案20】:

          我最喜欢的方式是使用Blessings 库(完全公开:我写的)。例如:

          from blessings import Terminal
          
          t = Terminal()
          print t.red('This is red.')
          print t.bold_bright_red_on_black('Bright red on black')
          

          要打印彩色砖块,最可靠的方法是使用背景颜色打印空间。我使用这种技术在nose-progressive中绘制进度条:

          print t.on_green(' ')
          

          您也可以在特定位置打印:

          with t.location(0, 5):
              print t.on_yellow(' ')
          

          如果您在游戏过程中不得不使用其他终端功能,您也可以这样做。你可以使用 Python 的标准字符串格式来保持它的可读性:

          print '{t.clear_eol}You just cleared a {t.bold}whole{t.normal} line!'.format(t=t)
          

          Blessings 的好处在于它尽最大努力在各种终端上工作,而不仅仅是(非常常见的)ANSI 色终端。它还可以将不可读的转义序列排除在您的代码之外,同时保持简洁易用。玩得开心!

          【讨论】:

          • 将颜色作为函数名而不是参数是有问题的做法。
          • @LtWorf:如果需要,您可以使用getattr 轻松将其设为参数。或者更有可能,只是动态地创建格式字符串。
          • @progo 您可以做到这一点并不意味着您应该这样做。如果颜色是您可以传递的参数,则更通用。
          • can just pass一个python函数。
          • 请注意,导入祝福在windows上不起作用,所以如果您的脚本需要跨平台,请不要使用它。
          【解决方案21】:

          试试这个简单的代码

          def prRed(prt): print("\033[91m {}\033[00m" .format(prt))
          def prGreen(prt): print("\033[92m {}\033[00m" .format(prt))
          def prYellow(prt): print("\033[93m {}\033[00m" .format(prt))
          def prLightPurple(prt): print("\033[94m {}\033[00m" .format(prt))
          def prPurple(prt): print("\033[95m {}\033[00m" .format(prt))
          def prCyan(prt): print("\033[96m {}\033[00m" .format(prt))
          def prLightGray(prt): print("\033[97m {}\033[00m" .format(prt))
          def prBlack(prt): print("\033[98m {}\033[00m" .format(prt))
          
          prGreen("Hello, World!")
          

          【讨论】:

          • 建议:定义返回该彩色字符串的 lambdas,而不是直接打印它们,以便与其他字符串一起使用。
          • 感谢@gustafbstron。这就是我决定使用的:def prGreen: return '"\033[91m {}\033[00m" .format(prt),这样使用:print(f'This will turn {prGreen("Hello world")} and change back')
          【解决方案22】:

          表情符号

          您可以像其他人在他们的答案中提到的那样为文本使用颜色,以获得带有背景或前景色的彩色文本。

          但您可以改用表情符号!例如,您可以将⚠️ 用于警告消息,将? 用于错误消息。

          或者简单地将这些笔记本用作颜色:

          ?: error message
          ?: warning message
          ?: ok status message
          ?: action message
          ?: canceled status message
          ?: Or anything you like and want to recognize immediately by color
          
          

          ? 奖励:

          此方法还可以帮助您直接在源代码中快速扫描和查找日志。

          但是某些操作系统(包括某些版本中带有一些窗口管理器的某些 Linux 发行版)默认的表情符号字体默认情况下是不彩色的,您可能希望首先让它们变得彩色。

          【讨论】:

          • 这不是被问到的,但我很高兴你分享了它!比起文字颜色,我真的更喜欢这个。
          • Linux?什么发行版、版本和窗口管理器? Ubuntu 20.04 (Focal Fossa)?
          • 答案已更新,更准确。感谢指出@PeterMortensen
          【解决方案23】:

          我有一个library called colorit。超级简单。

          这里有一些例子:

          from colorit import *
          
          # Use this to ensure that ColorIt will be usable by certain command line interfaces
          # Note: This clears the terminal
          init_colorit()
          
          # Foreground
          print(color("This text is red", Colors.red))
          print(color("This text is orange", Colors.orange))
          print(color("This text is yellow", Colors.yellow))
          print(color("This text is green", Colors.green))
          print(color("This text is blue", Colors.blue))
          print(color("This text is purple", Colors.purple))
          print(color("This text is white", Colors.white))
          
          # Background
          print(background("This text has a background that is red", Colors.red))
          print(background("This text has a background that is orange", Colors.orange))
          print(background("This text has a background that is yellow", Colors.yellow))
          print(background("This text has a background that is green", Colors.green))
          print(background("This text has a background that is blue", Colors.blue))
          print(background("This text has a background that is purple", Colors.purple))
          print(background("This text has a background that is white", Colors.white))
          
          # Custom
          print(color("This color has a custom grey text color", (150, 150, 150)))
          print(background("This color has a custom grey background", (150, 150, 150)))
          
          # Combination
          print(
              background(
                  color("This text is blue with a white background", Colors.blue), Colors.white
              )
          )
          
          # If you are using Windows Command Line, this is so that it doesn't close immediately
          input()
          

          这给了你:

          另外值得注意的是,这是跨平台的,并且已经在 Mac、Linux 和 Windows 上进行了测试。

          您可能想尝试一下:https://github.com/SuperMaZingCoder/colorit

          colorit 现在可以与 PyPi 一起安装!您可以在 Windows 上使用 pip install color-it 安装它,在 macOS 和 Linux 上使用 pip3 install color-it 安装它。

          【讨论】:

          • 什么时候可以使用 pip 安装它?
          • @ncopiy 你好!我实际上计划在接下来的两天内这样做! :D 现在,您可以按照页面上的安装说明进行安装。
          • @ncopiy 现在可以使用pip3(或pip)安装。命令为pip3 install color-itpip install color-it,可以用import colorit导入。
          • 我不知道为什么,但是我的文本没有被 Colors.etc 上提供的颜色着色...我所有的文本都变成了灰色文本,但色调不同(更亮/更暗)...
          • @Victor 嗯,假设您在某处有 init_colorit() 声明,它可能是您的终端。在其他终端有什么作用?
          【解决方案24】:

          注意with 关键字与需要重置的修饰符(使用 Python 3 和 Colorama)的混合效果:

          from colorama import Fore, Style
          import sys
          
          class Highlight:
            def __init__(self, clazz, color):
              self.color = color
              self.clazz = clazz
            def __enter__(self):
              print(self.color, end="")
            def __exit__(self, type, value, traceback):
              if self.clazz == Fore:
                print(Fore.RESET, end="")
              else:
                assert self.clazz == Style
                print(Style.RESET_ALL, end="")
              sys.stdout.flush()
          
          with Highlight(Fore, Fore.GREEN):
            print("this is highlighted")
          print("this is not")
          

          【讨论】:

          • 试用了 colorama,使用 print(Style.BRIGHT + "Header Test")print (Style.DIM + word) 创建了一个非常好的提示。
          • 这需要更改为使用 contextlib 用于 Py3。
          • @cat:需要从哪个版本的 Python 开始?
          • 我相信 3 及以上——它应该有一个 @contextlib.contextmanager 装饰器,不是吗?
          • @cat:为什么?没有效果很好。
          【解决方案25】:
          # Pure Python 3.x demo, 256 colors
          # Works with bash under Linux and MacOS
          
          fg = lambda text, color: "\33[38;5;" + str(color) + "m" + text + "\33[0m"
          bg = lambda text, color: "\33[48;5;" + str(color) + "m" + text + "\33[0m"
          
          def print_six(row, format, end="\n"):
              for col in range(6):
                  color = row*6 + col - 2
                  if color>=0:
                      text = "{:3d}".format(color)
                      print (format(text,color), end=" ")
                  else:
                      print(end="    ")   # four spaces
              print(end=end)
          
          for row in range(0, 43):
              print_six(row, fg, " ")
              print_six(row, bg)
          
          # Simple usage: print(fg("text", 160))
          

          Try it online

          【讨论】:

          • 格式非常好,而且有很多颜色范围。我一直在回来,谢谢!
          • 非常好,请给我一些关于"\33[38;5;" 的解释。
          • @Jay,这是escape sequence'\33' 是转义字符(八进制)。
          • 优秀的纯python解决方案。
          【解决方案26】:

          我已将 joeld's answer 包装到一个具有全局函数的模块中,我可以在代码中的任何位置使用它。

          文件:log.py

          def enable():
              HEADER = '\033[95m'
              OKBLUE = '\033[94m'
              OKGREEN = '\033[92m'
              WARNING = '\033[93m'
              FAIL = '\033[91m'
              ENDC = '\033[0m'
              BOLD = "\033[1m"
          
          def disable():
              HEADER = ''
              OKBLUE = ''
              OKGREEN = ''
              WARNING = ''
              FAIL = ''
              ENDC = ''
          
          def infog(msg):
              print(OKGREEN + msg + ENDC)
          
          def info(msg):
              print(OKBLUE + msg + ENDC)
          
          def warn(msg):
              print(WARNING + msg + ENDC)
          
          def err(msg):
              print(FAIL + msg + ENDC)
          
          enable()
          

          如下使用:

          import log
          log.info("Hello, World!")
          log.err("System Error")
          

          【讨论】:

            【解决方案27】:

            更简单的选择是使用 termcolor 包中的 cprint 函数。

            还支持%s, %d格式的打印:

            结果可能取决于终端,因此请查看包文档的终端属性部分。

            • Windows 命令提示符和 Python IDLE 不起作用

            • JupyterLab 笔记本可以正常工作

            【讨论】:

            【解决方案28】:

            如果您只想使用内置包,请遵循以下结构:

            实际上,我增强了Mohamed Samy 答案,它现在负责多个输入和数字。此外,它还支持其他print() 参数,例如end=。此外,我添加了一个.store() 方法,以便将日志也写入文件。

            您可以创建一个实用程序以在您的代码中的任何位置使用它:

            # utility.py
            
            from datetime import datetime
            
            class ColoredPrint:
                def __init__(self):
                    self.PINK = '\033[95m'
                    self.OKBLUE = '\033[94m'
                    self.OKGREEN = '\033[92m'
                    self.WARNING = '\033[93m'
                    self.FAIL = '\033[91m'
                    self.ENDC = '\033[0m'
            
                def disable(self):
                    self.PINK = ''
                    self.OKBLUE = ''
                    self.OKGREEN = ''
                    self.WARNING = ''
                    self.FAIL = ''
                    self.ENDC = ''
            
                def store(self):
                    date = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
                    with open('logfile.log', mode='a') as file_:
                        file_.write(f"{self.msg} -- {date}")
                        file_.write("\n")
            
                def success(self, *args, **kwargs):
                    self.msg = ' '.join(map(str, args))
                    print(self.OKGREEN + self.msg + self.ENDC, **kwargs)
                    return self
            
                def info(self, *args, **kwargs):
                    self.msg = ' '.join(map(str, args))
                    print(self.OKBLUE + self.msg + self.ENDC, **kwargs)
                    return self
            
                def warn(self, *args, **kwargs):
                    self.msg = ' '.join(map(str, args))
                    print(self.WARNING + self.msg + self.ENDC, **kwargs)
                    return self
            
                def err(self, *args, **kwargs):
                    self.msg = ' '.join(map(str, args))
                    print(self.FAIL + self.msg + self.ENDC, **kwargs)
                    return self
            
                def pink(self, *args, **kwargs):
                    self.msg = ' '.join(map(str, args))
                    print(self.PINK + self.msg + self.ENDC, **kwargs)
                    return self
            

            例如

            from utility import ColoredPrint
            
            log = ColoredPrint()
            
            log.success("Hello" , 123, "Bye").store()
            log.info("Hello" , 123, "Bye")
            log.warn("Hello" , 123, "Bye")
            log.err("Hello" , 123, "Bye").store()
            log.pink("Hello" , 123, "Bye")
            

            输出:


            [更新]:

            现在,它的 PyPI package? 可用:

            pip install python-colored-print
            

            【讨论】:

              【解决方案29】:

              这是一个简单的函数,用于打印彩色文本消息,无需记住 ANSI 代码,而是使用标准 RGB 元组来定义前景色和背景色。

              def print_in_color(txt_msg, fore_tuple, back_tuple, ):
                  # Prints the text_msg in the foreground color specified by fore_tuple with the background specified by back_tuple
                  # text_msg is the text, fore_tuple is foreground color tuple (r,g,b), back_tuple is background tuple (r,g,b)
                  rf,bf,gf = fore_tuple
                  rb,gb,bb = back_tuple
                  msg = '{0}' + txt_msg
                  mat = '\33[38;2;' + str(rf) + ';' + str(gf) + ';' + str(bf) + ';48;2;' + str(rb) + ';' +str(gb) + ';' + str(bb) + 'm'
                  print(msg .format(mat))
                  print('\33[0m') # Returns default print color to back to black
              
              # Example of use using a message with variables
              fore_color = 'cyan'
              back_color = 'dark green'
              msg = 'foreground color is {0} and the background color is {1}'.format(fore_color, back_color)
              print_in_color(msg, (0,255,255), (0,127,127))
              

              【讨论】:

                【解决方案30】:
                print("\033[1;32;40m Bright Green  \n")
                

                【讨论】:

                • 解释一下。
                猜你喜欢
                • 2010-09-22
                • 1970-01-01
                • 2017-07-17
                • 1970-01-01
                • 1970-01-01
                • 2021-12-04
                • 1970-01-01
                • 1970-01-01
                • 2011-02-06
                相关资源
                最近更新 更多