一个 Python 库,用于为您的控制台添加样式。
项目描述
康体
一个 Python 库,用于为您的控制台添加样式。
库的名称来自合并单词CONSoLE和STYLE。“con”在西班牙语中也意味着“with”。
安装
您可以使用 pip 或 conda 安装此软件包。
$ pip install constyle
$ conda install -c conda-forge constyle
$ conda install -c abrahammurciano constyle
链接
用法
有几种方法可以使用这个库。
style
功能_
最简单的方法是使用style
函数。
from constyle import style, Attributes
print(style('Hello World', Attributes.GREEN, Attributes.BOLD, Attributes.ON_BLUE))
Style
对象
您还可以使用Style
对象创建具有任意数量属性的可重用样式。
调用Style
对象
Style
对象是可调用的,并将字符串作为输入并返回一个样式化的字符串。
warning = Style(Attributes.YELLOW, Attributes.BOLD)
print(warning('You shall not pass!'))
添加Style
对象
将对象加在一起Style
也将创建Style
对象。
whisper = Attributes.GREY + Attributes.DIM + Attributes.SUPERSCRIPT
print(whisper('Fly you fools'))
将Style
对象转换为字符串
Style
可以将对象转换为字符串以获得该样式的 ANSI 转义序列。
warning = Style(Attributes.YELLOW, Attributes.BOLD)
print(f"{warning}You shall not pass!{Attributes.RESET}")
属性
枚举包含所有可用的Attributes
ANSI 属性。你可以在这里阅读更多关于它们的信息。
Attributes
也是Style
对象,因此,如上所示,它们也可以被调用来设置字符串的样式,添加到其他Style
对象中,然后转换为字符串以获得它们的 ANSI 序列。
您会发现某些控制台对所有 ANSI 属性的支持有限。
Style
如果您发现此枚举中未提供更多属性,您可以通过使用整数构造 a 来创建自己的属性。
嵌套
为了嵌套样式,您可以使用函数或类的end=
关键字参数。通常在应用样式时,属性会附加到末尾。这在嵌套时可能是不可取的(参见下面的示例)。style
Style
RESET
bold = Attributes.BOLD
yellow = Attributes.YELLOW
green = Attributes.GREEN
print(yellow(bold('This is bold and yellow')))
print(green(f"This is green. {yellow('This is yellow.')} This is no longer green"))
为了在上面的示例中获得所需的结果,您必须使用函数的end=
关键字参数style
。您可以将任何传递Style
给end
.
print(green(f"This is green. {bold('This is green and bold.', end=Attributes.NO_BOLD)} This is still green but not bold anymore"))
print(green(f"This is green. {yellow('This is yellow.', end=green)} This is now green again"))
自定义颜色
该constyle.custom_colours
模块包含一些可用于创建自定义颜色的类。
RGB 颜色
您可以Style
使用RGB
该类为自定义 RGB 颜色创建一个。并非所有控制台都很好地支持这一点。
from constyle.custom_colours import RGB
print(style('This is pink', RGB(255, 192, 203)))
8 位颜色
一些控制台支持 8 位颜色。您可以Style
通过使用该类为 8 位颜色创建一个EightBit
,将单个整数传递给它,或者您可以使用EightBitRGB
该类创建一个尽可能接近 RGB 值的 8 位颜色样式。
命令行界面
这个包还提供了一个非常基本的命令行界面来打印样式字符串。
您可以将任意数量的字符串传递给它,它会将它们一起打印(如echo
)。您可以传递--attribute
(或-a
)属性名称以应用于正在打印的其他字符串。您可以随意通过--attribute
多次。
您可以使用constyle --help
查看更具体的详细信息以及所有可用属性。
例如,您可以constyle
在 shell 中使用来打印一些样式化的文本。
$ constyle Hello World! -a green -a bold -a on_white
或者,如果您正在编写一个 shell 脚本,您可以创建一个别名或函数来重用某种样式。
#!/bin/bash
alias error="constyle --attribute bold --attribute red" # With an alias
warn() { constyle $@ -a bold -a yellow } # With a function
error You shall not pass!
warn Fly you fools!
项目详情
下载文件
下载适用于您平台的文件。如果您不确定要选择哪个,请了解有关安装包的更多信息。