ChatGPT解决这个技术问题 Extra ChatGPT

如何将彩色文本打印到终端?

如何在 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

P
Peter Mortensen

这在某种程度上取决于您所在的平台。最常见的方法是打印 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 是“块字符”。

一些现代的基于文本的程序,例如“Dwarf Fortress”,以图形模式模拟文本模式,并使用经典 PC 字体的图像。您可以在 Dwarf Fortress Wiki 查看 (user-made tilesets) 中找到其中一些可以使用的位图。

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


在 Linux 上,您可能希望使用 tputlike so,因为它会产生更多可移植的代码。
@Cawas:disable 的一个真正用例是将输出通过管道传输到文件时;虽然像 cat 这样的工具可能支持颜色,但通常最好不要将颜色信息打印到文件中。
@AlexanderSimko,这是在 Windows 10 中启用 VT100 支持的 ctypes 代码片段: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 范围内的颜色是 non-standard 并且实际上在我的终端上它们没有都给出由变量名称指示的颜色。最好使用标准范围 30-37 和 40-47。来源:en.wikipedia.org/wiki/…
M
Mahrkeenerh

还有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 转义序列开始工作。
J
JayRizzo

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

它支持 Python 3.5+ 以及 Python 2.7。

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

示例代码:

from colorama import Fore
from colorama import Style

print(f"This is {Fore.GREEN}color{Style.RESET_ALL}!")

https://i.stack.imgur.com/q3D4W.png


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

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

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

https://i.stack.imgur.com/RN3MN.png

使用以下代码获取 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://i.stack.imgur.com/6otvY.png

明暗示例(部分)

https://i.stack.imgur.com/lZr23.png

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


这适用于大多数 shell 以及 ipython,对于大多数应用程序来说已经足够了
请问,这是哪个终端?
它的便携性如何?
要在 Windows 10 Powershell 中完成这项工作,请在 Python 中导入 os,然后执行 os.system('color')。从那时起,ANSI 转义序列将神奇地起作用。
P
Peter Mortensen

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

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

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

https://i.stack.imgur.com/Iu3I1.png

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

https://i.stack.imgur.com/j7e4i.gif

注意:\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/…
S
SimpleBinary

这是一个原生适用于 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 代码,无论是通过系统调用还是模块。并非所有文本装饰都受支持,虽然显示的是亮色,但它们与常规颜色相同。

感谢@jl 找到了一个更短的方法。

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中使用ASNI代码运行printf(fmt, ...);的C中确实打印了彩色文本,我仍然很好奇为什么会这样?
P
Peter Mortensen

您想了解 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 将其打印为常规文本。
R
Rotareti

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

印刷:

https://i.stack.imgur.com/4BIdi.png

演示:

https://i.stack.imgur.com/S8wtO.png


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

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

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

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

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

https://i.stack.imgur.com/4jJaD.png


E
Erik Rose

我最喜欢的方式是使用 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 上不起作用,因此如果您的脚本需要跨平台,请不要使用它。
P
Peter Mortensen

我使用 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'

C
CircuitSacul

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

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

打印红色文本的示例:

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{text} \ 033[38;2;255;255;255m'
当前实现之后有一个副作用尾随空格。您可以通过从字符串格式中删除尾随空格来摆脱。改用这个: f"\033[38;2;{r};{g};{b}m{text}\033[38;2;255;255;255m"
@Elyasaf755 谢谢,已修复。
J
JayRizzo

试试这个简单的代码

def prRed(prt):
    print(f"\033[91m{prt}\033[00m")

def prGreen(prt):
    print(f"\033[92m{prt}\033[00m")

def prYellow(prt):
    print(f"\033[93m{prt}\033[00m")

def prLightPurple(prt):
    print(f"\033[94m{prt}\033[00m")

def prPurple(prt):
    print(f"\033[95m{prt}\033[00m")

def prCyan(prt):
    print(f"\033[96m{prt}\033[00m")

def prLightGray(prt):
    print(f"\033[97m{prt}\033[00m")

def prBlack(prt):
    print(f"\033[98m{prt}\033[00m")

def prReset(prt):
    print(f"\033[0m{prt}\033[00m")

prGreen("Hello, Green World!")
prBlack("Hello, Black World!")
prCyan("Hello, Cyan World!")
prGreen("Hello, Green World!")
prLightGray("Hello, Light Grey World!")
prLightPurple("Hello, Light Purple World!")
prPurple("Hello, Purple World!")
prRed("Hello, Red World!")
prYellow("Hello, Yellow World!")
prReset("Hello, Reset World!")

https://i.stack.imgur.com/VsUHx.png

# python2
    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')
P
Peter Mortensen

我有一个 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()

这给了你:

https://i.stack.imgur.com/AESCH.png

还值得注意的是,这是跨平台的,并且已经在 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() 语句,它可能是您的终端。它在其他终端有什么作用?
A
Andriy Makukha
# 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))

https://i.stack.imgur.com/qqMmX.png

Try it online


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

在 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
P
Peter Mortensen

我已将 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")

V
Vishal
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 的公认答案。完美运行。
P
Peter Mortensen

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

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

Colors

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

#

在 Windows 10 中,如果您在代码开头调用 os.system(''),颜色会像 linux 一样工作
P
Peter Mortensen

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

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)

在没有第三方软件包的情况下这样做真的很好。
b
bluenote10

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

它是为数不多的正确支持嵌套样式的库之一:

https://i.stack.imgur.com/piYe5.png

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

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

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

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

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

在语法上更详细,因为必须明确指定重置,

更容易出错,因为您可能会不小心忘记重置样式,

无法正确处理边缘情况:例如,在某些终端中,必须在换行之前重置样式,并在换行后重新激活它们。此外,一些终端在简单地覆盖互斥样式方面存在问题,并且需要插入“不必要的”重置代码。如果开发者的本地终端没有这些怪癖,开发者不会立即发现这些怪癖。该问题只会在稍后由其他人报告或导致问题,例如在 CI 终端上。

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

为什么还有一个图书馆?

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

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

有色

异色

术语颜色

颜色

麦粒肿

祝福

富有的

颜色

彩印

控制台颜色

玩偶

颜色

样式(以前称为 clr)

pychalk

简单的粉笔

chlk

白垩


但你似乎错过了多彩,github.com/timofurrer/colorful
P
Peter Mortensen

非常简单,基于 joeld's answer

class PrintInColor:
    RED = '\033[91m'
    GREEN = '\033[92m'
    YELLOW = '\033[93m'
    LIGHT_PURPLE = '\033[94m'
    PURPLE = '\033[95m'
    END = '\033[0m'

    @classmethod
    def red(cls, s, **kwargs):
        print(cls.RED + s + cls.END, **kwargs)

    @classmethod
    def green(cls, s, **kwargs):
        print(cls.GREEN + s + cls.END, **kwargs)

    @classmethod
    def yellow(cls, s, **kwargs):
        print(cls.YELLOW + s + cls.END, **kwargs)

    @classmethod
    def lightPurple(cls, s, **kwargs):
        print(cls.LIGHT_PURPLE + s + cls.END, **kwargs)

    @classmethod
    def purple(cls, s, **kwargs):
        print(cls.PURPLE + s + cls.END, **kwargs)

然后就

PrintInColor.red('hello', end=' ')
PrintInColor.green('world')

如果您传递多个位置参数或字符串类型以外的任何内容,这将崩溃
@RomainVincent 然后不要传递多个位置参数或字符串 ty 以外的任何内容——等等,这些是 print-replacements?异议被撤销。
@wizzwizz4 我不确定你对这个评论的意思,反正我不明白这一点。如果您要提出一个类...,以替换像 print 这样简单的方法,您最好避免让它变得如此容易破坏。只是我的观点。
@RomainVincent 我要说您的反对意见是错误的,但是要替换像 print 这样通用的功能,应该确保正确复制其功能。
@RomainVincent 实现使用无限参数:<code> def purple(cls, *args, **kwargs): print(cls.PURPLE, *args, cls.END, **kwargs) </code>
P
Peter Mortensen

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

截屏:

https://i.stack.imgur.com/9NgeB.png

使用新格式化程序对 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

截屏:

https://i.stack.imgur.com/HGNPc.png


P
Peter Mortensen

请注意 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) 创建了一个非常好的提示。
这需要更改为对 Py3 使用 contextlib
@cat:需要什么版本的 Python?
我相信 3 及以上——它应该有一个 @contextlib.contextmanager 装饰器,不是吗?
@cat:为什么?没有效果很好。
P
Peter Mortensen

您可以使用 Clint

from clint.textui import colored
print colored.red('some warning message')
print colored.green('nicely done!')

第一个链接消失了,所以我删除了它; GH链接仍然很好(尽管该项目已“存档”并且基本上被放弃,据我所知)。
P
Peter Mortensen

您可以使用 curses 库的 Python 实现:curses — Terminal handling for character-cell displays

另外,运行这个,你会找到你的盒子:

for i in range(255):
    print i, chr(i)

就我个人而言,我认为'curses'库已经完全被'blessings'所掩盖,就像'requests'已经让'urllib'黯然失色,等等。
A
Andy Hayden

如果您正在编写游戏,也许您想更改背景颜色并仅使用空格?例如:

print " "+ "\033[01;41m" + " " +"\033[01;46m"  + "  " + "\033[01;42m"

可以在此处找到更多信息 - linux.byexamples.com/archives/184/…
T
Trenton McKinney

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

https://i.stack.imgur.com/v35jK.png

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

https://i.stack.imgur.com/BvgXH.png

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

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

https://i.stack.imgur.com/46mp4.png

https://i.stack.imgur.com/4A7ug.png

JupyterLab 笔记本确实有效

https://i.stack.imgur.com/kFhyO.png


如果您正在寻找 windows 10 的解决方案,请看这里 => stackoverflow.com/a/70599663/3057246
M
Mojtaba Hosseini

表情符号

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

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

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

📕: error message
📙: warning message
📗: ok status message
📘: action message
📓: canceled status message
📔: Or anything you like and want to recognize immediately by color

🎁 奖励:

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

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

如何打开表情符号选择器?

mac os: 控制 + 命令 + 空格

windows: win + .

linux: control + .control + ;


这不是被问到的,但我很高兴你无论如何都分享了它!我真的更喜欢这个而不是文字颜色。
Linux?什么发行版、版本和窗口管理器? Ubuntu 20.04 (Focal Fossa)
答案更新更准确。感谢指出@PeterMortensen
您说“您可以使用 [...]”,但我没有看到有关如何执行此操作的解释?我错过了什么吗?任何链接、库、代码等解释如何做你提到的?
表情符号是 unicode。您可以通过搜索“emoji”在线了解更多信息😉
P
Peter Mortensen

耶!另一个版本

虽然我发现 this answer 有用,但我对其进行了一些修改。这个 GitHub Gist 是结果

用法

print colors.draw("i'm yellow", bold=True, fg_yellow=True)

https://i.stack.imgur.com/q1mJ3.png

此外,您可以包装常见的用法:

print colors.error('sorry, ')

https://i.stack.imgur.com/uGgd7.png

https://gist.github.com/Jossef/0ee20314577925b4027f