Python输出还可以这么花里胡哨,这个第三方库值得你了解一下
大家好,我是村长。
最近后知后觉看到一个花里胡哨的rich
库,可以让你的控制台输出结果美妙绝伦!!
如果你也还不知道这库的存在,倒是可以一看究竟,没准也会喜欢上她!
Rich 是一个 Python 库,可以为您在终端中提供富文本和精美格式。
Rich API可以很容易的在终端输出添加各种颜色和不同风格。Rich 还可以绘制漂亮的表格,进度条,markdown,突出显示语法的源代码及回溯等等,不胜枚举。
Rich 适用于 Linux,OSX 和 Windows。真彩色/表情符号可与新的 Windows 终端一起使用,Windows 的经典终端仅限 8 种颜色。
Rich 还可以与Jupyter 笔记本一起使用,而无需其他配置。
目录:
1. 准备工作
2. Rich的功能特色
3. 功能演示
3.1. 颜色与样式
3.2. 文本格式
3.3. 文本高亮
3.4. 输入提示
3.5. 表情符号
3.6. 表格
3.7. 语法高亮
3.8. markdown格式输出
3.9. 进度条
3.10. 树结构
+ More
本文演示环境:
JupyterLab = 3.0.11
,主题为暗色
1. 准备工作
安装rich
库
pip install rich
简单的例子
from rich import print
print("[italic red]Hello[/italic red] World!")

我们可以看到,上面例子中输出的Hello World中Hello被设置为红色斜体,World为默认值。
再看一个例子
from rich.panel import Panel
Panel.fit("[bold yellow]Hi, I'm a Panel", border_style="red")

这个例子,我们采用了Panel(面板),面板的轮廓为红色,内容文案为加粗的黄色。
以上只是简单介绍两个小例子,接下来我们来看看Rich是如何rich各种精美的输出吧!
2. Rich的功能特色
在jupyterlab里运行(截图是在jupyterlab暗黑主题下截取)
%run -m rich
在cmd终端里运行
python -m rich
可以得到下面这个展示rich库功能特色的简要说明,我们能清晰的看出它所具备的及支持的精美格式诸如:
颜色 样式 文本对齐方式 多语言支持 标记符号&表情 表格 语法高亮 markdown 进度条 ...+more

3. 功能演示
我们这里只做简单的功能案例演示,详细的使用大家可以直接查看官方文档。
https://rich.readthedocs.io/en/stable/
3.1. 颜色与样式
我们先构造一个控制台对象,然这个对象有一个print方法,和python内置的功能基本一致。和内置的不同在于Rich会将文字自动换行以适合终端宽度,并且有几种方法可以为输出添加颜色和样式。
from rich.console import Console
console = Console()
console.print("Hello", style="magenta")

可以看到,输出的Hello是酒红色的,颜色通过style参数设置,这里颜色是英文单词,同时也可以是16进制颜色码、RGB或者颜色color(n)表示等等。
console.print("Rich库有点意思啊", style="red on white")

上面这个例子,我们发现还可以通过style设置文本颜色及底色。
另外,我们还可以这样设置文本样式:通过[red]
与 [/red]
来设置其框定的区域文本颜色与样式。
from rich import print
print("[bold red]alert![/bold red] Something happened")

3.2. 文本格式
Rich有个Text类,用于我们对长文本进行颜色与样式调整。
from rich.console import Console
from rich.text import Text
console = Console()
text = Text("0123456789")
text.stylize("bold magenta", 0, 6)
console.print(text)

对于上面这个案例,将字符串0123456789
中[0,6)
下标的字符颜色设置为酒红色粗体。
from rich import print
from rich.panel import Panel
from rich.text import Text
panel = Panel(Text("大家好,我是才哥。欢迎关注微信公众号:可以叫我才哥!", justify="center"))
print(panel)

这个例子中,我们可以看到它是将文本居中对齐在一个面板中。
3.3. 文本高亮
Rich可以通过正则或者其他形式让文本中指定的字符高亮。
比如,我们通过正则让文本中邮箱字符高亮:
from rich.console import Console
from rich.highlighter import RegexHighlighter
from rich.theme import Theme
class EmailHighlighter(RegexHighlighter):
"""Apply style to anything that looks like an email."""
base_style = "example."
highlights = [r"(?P<email>[\w-]+@([\w-]+\.)+[\w-]+)"]
theme = Theme({"example.email": "bold magenta"})
console = Console(highlighter=EmailHighlighter(), theme=theme)
console.print("Send funds to money@example.org")

比如,我们可以将文本每个字符设置成随机的颜色:
from random import randint
from rich import print
from rich.highlighter import Highlighter
class RainbowHighlighter(Highlighter):
def highlight(self, text):
for index in range(len(text)):
text.stylize(f"color({randint(16, 255)})", index, index + 1)
rainbow = RainbowHighlighter()
print(rainbow("大家好,我是才哥,是不是每个字的颜色都不一样?"))

3.4. 输入提示
Rich有个Prompt类,用于提示我们进行输入(类似input功能),不过它还支持指定值输入及选择判断等。
提示输入:
from rich.prompt import Prompt
name = Prompt.ask("Enter your name")

指定值输入:
from rich.prompt import Prompt
name = Prompt.ask("Enter your name", choices=["才哥", "可以叫我才哥", "天才"], default="可以叫我才哥")

选择判断:
from rich.prompt import Confirm
is_rich_great = Confirm.ask("Do you like rich?")
assert is_rich_great

3.5. 表情符号
将名称放在两个冒号之间即可在控制台输出中插入表情符号。
from rich.console import Console
console = Console()
console.print(":smiley: :pile_of_poo: :thumbs_up: ")

3.6. 表格
Rich 可以使用 Unicode 框字符来呈现多变的表格,它包含多种边框,样式,单元格对齐等格式设置的选项。
from rich.console import Console
from rich.table import Table
table = Table(title="Star Wars Movies")
table.add_column("Released", justify="right", style="cyan", no_wrap=True)
table.add_column("Title", style="magenta")
table.add_column("Box Office", justify="right", style="green")
table.add_row("Dec 20, 2019", "Star Wars: The Rise of Skywalker", "$952,110,690")
table.add_row("May 25, 2018", "Solo: A Star Wars Story", "$393,151,347")
table.add_row("Dec 15, 2017", "Star Wars Ep. V111: The Last Jedi", "$1,332,539,889")
table.add_row("Dec 16, 2016", "Rogue One: A Star Wars Story", "$1,332,439,889")
console = Console()
console.print(table)

3.7. 语法高亮
Rich 使用pygments库来实现语法高亮显示
from rich.console import Console
from rich.syntax import Syntax
my_code = '''
def iter_first_last(values: Iterable[T]) -> Iterable[Tuple[bool, bool, T]]:
"""Iterate and generate a tuple with a flag for first and last value."""
iter_values = iter(values)
try:
previous_value = next(iter_values)
except StopIteration:
return
first = True
for value in iter_values:
yield first, False, previous_value
first = False
previous_value = value
yield first, True, previous_value
'''
syntax = Syntax(my_code, "python", theme="monokai", line_numbers=True)
console = Console()
console.print(syntax)

3.8. markdown格式输出
Rich 可以呈现markdown,并可相当不错的将其格式转移到终端。为了渲染 markdown,导入Markdown
类,并使用包含 markdown 代码的字符串来构造它,然后将其打印到控制台。
MARKDOWN = """
# 这是一级标题
Rich 库能比较**完美**的输出markdown.
1. This is a list item
2. This is another list item
```python
from rich.console import Console
from rich.markdown import Markdown
console = Console()
md = Markdown(MARKDOWN)
console.print(md)
```

"""
from rich.console import Console
from rich.markdown import Markdown
console = Console()
md = Markdown(MARKDOWN)
console.print(md)

3.9. 进度条
Rich 可以渲染多个不闪烁的进度条形图,以跟踪长时间运行的任务。基本用法:用track
函数调用任何程序并迭代结果。
from rich.progress import track
import time
for step in track(range(100)):
time.sleep(0.1)

3.10. 树结构
Rich有个Tree类,用于展示树结构。
from rich.tree import Tree
from rich import print
tree = Tree("地球")
baz_tree = tree.add("亚洲")
baz_tree.add("[red]中国").add("[green]北京").add("[yellow]海淀区")
print(tree)

+ More
Padding
填充:
from rich import print
from rich.padding import Padding
test = Padding("Hello", (2, 4), style="on blue", expand=False)
print(test)

Panel
面板:
from rich import print
from rich.panel import Panel
print(Panel("Hello, [red]World!", title="Welcome"))

layout
布局:
from rich import print
from rich.layout import Layout
layout = Layout()
layout.split_column(
Layout(name="upper",size = 10),
Layout(name="lower",size = 10)
)
layout["lower"].split_row(
Layout(name="left"), Layout(name="right"),
)
layout["right"].split(
Layout(Panel("Hello")),
Layout(Panel("World!"))
)
print(layout)

Live
动态:
import time
from rich.live import Live
from rich.table import Table
table = Table()
table.add_column("Row ID")
table.add_column("Description")
table.add_column("Level")
with Live(table, refresh_per_second=4): # update 4 times a second to feel fluid
for row in range(12):
time.sleep(0.4) # arbitrary delay
# update the renderable internally
table.add_row(f"{row}", f"description {row}", "[red]ERROR")


分享、在看与点赞
爱你一万年~
