跳转到主要内容

在Python中正确完成终端字符串样式。

项目描述

colorful

Actions Status codecov.io PyPI version PyPI PyPI

在Python中正确完成终端字符串样式 :tada

这里有一些预告

colorful example

import colorful as cf

# create a colored string using clever method translation
print(cf.bold_white('Hello World'))
# create a colored string using `str.format()`
print('{c.bold}{c.lightCoral_on_white}Hello World{c.reset}'.format(c=cf))

# nest colors
print(cf.red('red {0} red'.format(cf.white('white'))))
print(cf.red('red' + cf.white(' white ', nested=True) + 'red'))

# combine styles with strings
print(cf.bold & cf.red | 'Hello World')

# use true colors
cf.use_true_colors()

# extend default color palette
cf.update_palette({'mint': '#c5e8c8'})
print(cf.mint_on_snow('Wow, this is actually mint'))

# choose a predefined style
cf.use_style('solarized')
# print the official solarized colors
print(cf.yellow('yellow'), cf.orange('orange'),
    cf.red('red'), cf.magenta('magenta'),
    cf.violet('violet'), cf.blue('blue'),
    cf.cyan('cyan'), cf.green('green'))

# directly print with colors
cf.print('{c.bold_blue}Hello World{c.reset}')

# choose specific color mode for one block
with cf.with_8_ansi_colors() as c:
    print(c.bold_green('colorful is awesome!'))

# create and choose your own color palette
MY_COMPANY_PALETTE = {
    'companyOrange': '#f4b942',
    'companyBaige': '#e8dcc5'
}
with cf.with_palette(MY_COMPANY_PALETTE) as c:
    print(c.companyOrange_on_companyBaige('Thanks for choosing our product!'))

# use f-string (only Python >= 3.6)
print(f'{cf.bold}Hello World')

# support for chinese
print(cf.red('你好'))

主要功能

  • 表达性和一致的API (文档)
  • 支持不同的颜色模式(8 ANSI,256 ANSI,真彩色)(文档)
  • 支持预定义的精彩样式(solarized,...)(文档)
  • 支持自定义颜色调色板(文档)
  • 支持嵌套样式(文档)
  • 支持不同的平台(在Windows上使用colorama)
  • 清理颜色模式、颜色调色板或样式切换的上下文管理器(文档
  • 支持对彩色字符串使用 len()文档
  • 支持来自 X11 rgb.txt 的颜色名称(文档
  • 无依赖项

用法

colorful 支持所有主要的 Python 版本:3.53.63.73.83.93.103.113.12
我们建议使用在 PyPI 上发布的最新版本

pip install colorful

colorful 使用时无需任何特殊设置

import colorful as cf

print(cf.italic_coral_on_beige('Hello World'))
print(cf.italic & cf.coral_on_beige | 'Hello World')
print('{c.italic_coral_on_beige}Hello World{c.reset}'.format(c=cf))

注意:整个文档假设 colorfulcf 的形式导入。

有关更多信息,请参阅 样式化字符串 部分!

颜色模式

如今,终端不仅支持古老的 8 种 ANSI 颜色,而且通常支持高达 1600 万种颜色,具有 真彩色。如果它们不支持 真彩色,则至少支持 256 ANSI 颜色调色板

colorful 支持以下颜色模式

  • 无颜色/禁用(cf.NO_COLORS
  • 8 种颜色 -> 8 种 ANSI 颜色(cf.ANSI_8_COLORS
  • 256 种颜色 -> 256 种 ANSI 颜色调色板(8 位 cf.ANSI_256_COLORS
  • 16777215 种颜色 -> 真彩色(24 位,cf.TRUE_COLORS

默认情况下,colorful 尝试自动检测终端支持的最佳颜色模式。有关详细信息,请参阅 cf.terminal

然而,有时指定应使用哪种颜色模式是有意义的。
colorful 提供了多种方式来实现这一点

(1) 通过 Python API 全局指定颜色模式

cf.disable()
cf.use_8_ansi_colors()
cf.use_256_ansi_colors()
cf.use_true_colors()

如果您在运行时更改颜色模式,则更改将立即并全局生效。

(2) 通过环境变量全局强制执行颜色模式

COLORFUL_DISABLE=1 python eggs.py  # this process will not use ANY coloring
COLORFUL_FORCE_8_COLORS=1 python eggs.py  # this process will use 8 ANSI colors by default
COLORFUL_FORCE_256_COLORS=1 python eggs.py  # this process will use 256 ANSI colors by default
COLORFUL_FORCE_TRUE_COLORS=1 python eggs.py  # this process will use true colors by default

(3) 通过 Python API(上下文管理器)局部指定颜色模式

with cf.with_8_ansi_colors() as c:
    print(c.italic_coral_on_beige('Hello world'))

with cf.with_256_ansi_colors() as c:
    print(c.italic_coral_on_beige('Hello world'))

with cf.with_true_colors() as c:
    print(c.italic_coral_on_beige('Hello world'))

颜色调色板

colorful 的 Python API 基于类似于 cf.bold_white_on_black('Hello') 中的 颜色名称。在运行时,这些 颜色名称 被转换为所使用的 颜色模式 支持的适当的 ANSI 转义序列。然而,所有 颜色名称 都注册在 颜色调色板 中,它基本上是 颜色名称 和其相应的 RGB 值之间的映射。非常类似于这样

color_palette_example = {
    'black': '#000000',
    'white': '#FFFFFF',
}

注意:根据所使用的颜色模式,RGB 值将缩减以适应颜色模式的值域。

默认颜色调色板是 X11 rgb.txt 调色板——它随 colorful 一起提供,因此您无需提供自己的。 colorful 还附带了一个内置的 颜色调色板,称为 colornames。这些颜色来自 color-names 存储库精心挑选的列表。您可以通过 cf.setup() 方法使用这些颜色,如下所示

cf.setup(colorpalette=cf.COLORNAMES_COLORS)

如果您希望将文件作为默认颜色调色板,可以将 COLORFUL_DEFAULT_COLOR_PALETTE 环境变量设置为该文件

COLORFUL_DEFAULT_COLOR_PALETTE=/usr/share/X11/rgb.txt python spam.py

该文件必须是类似于 X11 rgb.txt 的 txt 文件或 JSON 文件

[
    {"name": "18th Century Green", "hex":"#a59344"},
    {"name": "1975 Earth Red", "hex":"#7a463a"}
]

自定义颜色调色板

colorful 支持使用自定义颜色更新或替换默认颜色调色板。颜色必须指定为 RGB 十六进制或通道值

# corporate identity colors
ci_colors = {
    'mint': '#c5e8c8',  # RGB hex value
    'darkRed': '#c11b55',  # RGB hex value
    'lightBlue': (15, 138, 191)  # RGB channel triplet
}

# replace the default palette with my custom one
cf.use_palette(ci_colors)
# update the default palette with my custom one
cf.update_palette(ci_colors)

# we can use these colors
print(cf.italic_mint_on_darkRed('My company'))

样式

colorful 支持一些著名的颜色调色板,使用 colorful 中的 样式

cf.use_style('solarized')

# print the official solarized colors
print(cf.yellow('yellow'), cf.orange('orange'),
    cf.red('red'), cf.magenta('magenta'),
    cf.violet('violet'), cf.blue('blue'),
    cf.cyan('cyan'), cf.green('green'))

以下样式已支持

solarized - 网站
solarized colors
monokai
monokai colors

注意:如果您知道一些令人惊叹的色彩搭配,这些搭配可能成为新的多彩风格,请贡献出来!

样式字符串

colorful 提供多种方式来样式化字符串。最常用且表达性最强的是 方法语法,您可以直接在方法名中指定修饰符和颜色,并将字符串作为参数传递给该方法。然而,您也可以使用以下所有方法来达到类似的效果。

(1) 使用方法调用样式字符串 cf.[<modifiers...>]_[<fgColor>]_[on_<bgColor>](str, nested=False)

print(cf.red('I am red'))
print(cf.italic_yellow('I am italic and yellow'))
print(cf.black_on_white('I am black on white'))

方法语法可以是以下之一:

  • cf.<modifier>
  • cf.<modifier1>_<modifier2>
  • cf.<fg_color>
  • cf.on_<bg_color>
  • cf.<modifiers>_<fg_color>
  • cf.<modifiers>_<bg_color>
  • cf.<fg_colors>_on_<bg_color>
  • cf.<modifiers>_<fg_color>_on_<bg_color>

注意,可以同时指定多个 <modifier>

可用的修饰符有:

  • reset (明确重置传递参数之前的所有样式)
  • bold
  • dimmed (不受广泛支持)
  • italic
  • underlined
  • blinkslow
  • blinkrapid
  • inversed (不受广泛支持)
  • concealed (不受广泛支持)
  • struckthrough

可用的颜色取决于您所使用的 色彩搭配。默认情况下,所有 X11 rgb.txt 颜色 都可用。

此类 样式方法 的返回值类型为 colorful.ColorfulString。它正确支持所有 str() 方法,包括 len()

如您在章节标题的语法中所见,colorful 支持嵌套样式。请参阅 嵌套样式

(2) 使用 &| 样式字符串

colorful 实现了 __or____and__ 协议,以组合样式并将字符串管道化到其中

print(cf.bold & cf.red | 'Hello World')
print(cf.bold_red_on_black | 'Hello World')
print(cf.bold | cf.red_on_black('Hello World')

注意:管道 | 与对样式进行方法调用的效果相同。
因此,您可以这样做 (cf.bold & cf.red)('Hello World')

(3) 使用 cf.format(string, *args, **kwargs) 样式字符串

print(cf.format('{c.red}I am {what}{c.close_fg_color}', what='red'))
# alternatively to ``c.close_fg_color`` you can reset every style with ``c.reset``
print(cf.format('{c.red}I am red{c.reset}'))

print(cf.format('{c.italic_yellow}I am italic and yellow{c.no_italic}{c.close_fg_color}'))
print(cf.format('{c.black_on_white}I am black on white{c.close_fg_color}{c.close_bg_color}'))

colorful 将替换 {c.<style>} 为相应的样式。不需要为 c 传递彩色对象给 format() - colorful 会处理这个问题。其他格式参数(如 {<name>})必须作为 argskwarg 传递给 cf.format() 调用。

注意:在 {c.<style>} 中的样式语法、修饰符和颜色与 (1) 使用方法调用样式字符串 中的语法相同。

(4) 使用 cf.print(*strings, sep=' ', end='\n', file=sys.stdout, flush=False) 样式并打印字符串

cf.print('{c.italic_yellow}I am italic and yellow{c.no_italic}{c.close_fg_color}')
cf.print('{c.red}I am red{c.reset}', end='', file=open('log.txt', 'a+'))

cf.print() 方法接受与 Python 3.X 内置的 print() 函数 相同的参数。

(5) 使用 str.format() 样式字符串

print('{c.red}I am red{c.close_fg_color}'.format(c=cf))
# alternatively to ``c.close_fg_color`` you can reset every style with ``c.reset``
print('{c.red}I am red{c.reset}'.format(c=cf))

print('{c.italic_yellow}I am italic and yellow{c.no_italic}{c.close_fg_color}'.format(
    c=cf))
print('{c.black_on_white}I am black on white{c.close_fg_color}{c.close_bg_color}'.format(
    c=cf))

注意:在 {c.<style>} 中的样式语法、修饰符和颜色与 (1) 使用方法调用样式字符串 中的语法相同。

嵌套样式

colorful 支持在设置参数 nestedTrue 时使用其 方法调用语法 来嵌套样式。如果您像下面的第一个示例那样使用 str.format(),甚至不需要 nested=True 标志!

以下示例显示了这种行为

print(cf.red('red {0} red'.format(cf.white('white'))))
print(cf.red('red' + cf.white(' white ', nested=True) + 'red'))

# if using ``nested=True`` but you don't actually nest
# it's absolutely fine and will work as expected.
print(cf.red('red', nested=True) + ' default color')

正确支持 len() 协议

colorful 正确支持了 len() 协议(__len__)在样式化字符串上。如上所述,当你样式化一个字符串时,会返回一个 colorful.ColorfulString 对象。该对象在调用 len() 时会返回长度,就像 未样式化字符串 一样,以便无缝地将样式化字符串集成到你的应用程序中。

>>> s = 'Hello World'
>>> len(s)
11
>>> len(cf.yellow(s))
11
>>> assert len(s) == len(cf.yellow(s))

临时更改 colorful 设置

colorful 提供了一系列方便的上下文管理器来临时更改 colorful 设置。

(1) 更改颜色模式

使用 8 ANSI 颜色

with cf.with_8_ansi_colors() as c:
    print(c.red('I am red'))

使用 256 ANSI 颜色

with cf.with_256_ansi_colors() as c:
    print(c.red('I am red'))

使用真彩色

with cf.with_true_colors() as c:
    print(c.red('I am red'))

(2) 更改调色板

# replace the entire color palette
with cf.with_palette(my_palette) as c:
    print(c.customRed('I am custom red'))

# update the color palette
with cf.with_updated_palette(my_palette) as c:
    print(c.customRed('I am custom red'))

(3) 更改样式

with cf.with_style('solarized') as c:
    print(c.red('I am solarized red'))

本项目采用 MIT 许可协议发布。
一个 Timo Furrer 项目。
- :tada: -

项目详情


下载文件

下载适合您平台的文件。如果您不确定选择哪个,请了解更多关于 安装软件包 的信息。

源代码发行版

colorful-0.5.6.tar.gz (209.3 kB 查看哈希)

上传时间 源代码

构建发行版

colorful-0.5.6-py2.py3-none-any.whl (201.4 kB 查看哈希)

上传时间 Python 2 Python 3

支持者

AWS AWS 云计算和安全赞助商 Datadog Datadog 监控 Fastly Fastly CDN Google Google 下载分析 Microsoft Microsoft PSF 赞助商 Pingdom Pingdom 监控 Sentry Sentry 错误日志 StatusPage StatusPage 状态页面