gpt4 book ai didi

python - 标准库中某处是否有 ANSI 颜色转义码列表?

转载 作者:太空宇宙 更新时间:2023-11-03 13:37:37 24 4
gpt4 key购买 nike

我写了很多小帮助脚本,并且经常在终端中打印彩色文本。为了简化打包和分发,我经常希望这些小脚本没有任何依赖关系。

因此我在脚本中大量复制这样的数据:

ansi_colors = {
None: '\x1b[0m', # actually black but whatevs
'red': '\x1b[31m',
'green' : '\x1b[32m',
...
}

这些数据是否存在于核心库中的任何地方?我四处寻找,发现 curses 有一些 COLOR_* 常量,但它们只是整数,而且它们如何转换为 ANSI 转义码并不明显。

我已经知道 termcolorcoloramablessings 等模块,所以请不要建议使用它们 - 我想要仅依赖于标准库。

最佳答案

您可以查看手册页 console_codes(4) .您想要的是 ECMA-48 Set Graphics Rendition:

The ECMA-48 SGR sequence ESC [ parameters m sets display attributes. Several attributes can be set in the same sequence, separated by semicolons. An empty parameter (between semicolons or string initiator or terminator) is interpreted as a zero.

   param   result
0 reset all attributes to their defaults
1 set bold
2 set half-bright (simulated with color on a color display)
4 set underscore (simulated with color on a color display) (the colors used to
simulate dim or underline are set using ESC ] ...)
5 set blink
7 set reverse video
10 reset selected mapping, display control flag, and toggle meta flag (ECMA-48
says "primary font").
11 select null mapping, set display control flag, reset toggle meta flag
(ECMA-48 says "first alternate font").
12 select null mapping, set display control flag, set toggle meta flag (ECMA-48
says "second alternate font"). The toggle meta flag causes the high bit of a
byte to be toggled before the mapping table translation is done.
21 set normal intensity (ECMA-48 says "doubly underlined")
22 set normal intensity
24 underline off
25 blink off
27 reverse video off
30 set black foreground
31 set red foreground
32 set green foreground
33 set brown foreground
34 set blue foreground
35 set magenta foreground
36 set cyan foreground
37 set white foreground
38 set underscore on, set default foreground color
39 set underscore off, set default foreground color
40 set black background
41 set red background
42 set green background
43 set brown background
44 set blue background
45 set magenta background
46 set cyan background
47 set white background
49 set default background color

我不认为它们可以在任何标准 Python 模块中按原样使用。但是如果你仔细观察,你会注意到前景色是 30 加上 curses 常量,而背景色是 40 加上curses 常量。所以你可以这样写:

import curses
def fcolor(c):
return '\x1B[{0}m'.format(30 + c)
def bcolor(c):
return '\x1B[{0}m'.format(40 + c)
def fbcolor(f, b):
return '\x1B[{0};{1}m'.format(30 + f, 40 + b)

print(fbcolor(curses.COLOR_RED, curses.COLOR_YELLOW) + "hello!")

关于python - 标准库中某处是否有 ANSI 颜色转义码列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37170990/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com