Pretty Printing
除了语法高亮,Rich 还会为容器类型(list, dict, set)进行格式化
Run the following command to see an example of pretty printed output:
python -m rich.pretty
pprint method
pprint()
方法 提供了一些参数用来调整对象的打印方式
>>> from rich.pretty import pprint
>>> pprint(locals())
Indent guides
Indent guides 设置可以高亮锁紧部分,使我们更容易阅读更深层次的嵌套输出。
pprint 方法默认启用缩进指南。你可以设置 indent_guides=False
来禁用这个功能。
Expand all
Rich 在扩展数据结构方面是相当保守的,它将尽量在每一行中容纳更多的数据。你可以通过设置 expand_all=True
来告诉 Rich 完全展开所有数据结构。
>>> pprint(["eggs", "ham"], expand_all=True)
Truncating pretty output
长数据结构可能难以阅读,需要滚动页面才能找到自己想要的数据;Rich 可以截断容器和长字符串,让你在不影响终端的情况下获得概览
如果您将 max_length
参数设置为一个整数
- 超过长度的容器类型将会被截断;并显示一个省略号 “......” 以及未显示的元素数量。
>>> pprint(locals(), max_length=2)
- 超过长度的 str 类型将会被截断,并显示 “+” 号以及未显示的字符数量
>>> pprint("Where there is a Will, there is a Way", max_string=21)
Pretty renderable
Pretty
类用于来将 pretty printing data 插入到另一个可渲染数据中。
from rich import print
from rich.pretty import Pretty
from rich.panel import Panel
pretty = Pretty(locals())
panel = Panel(pretty)
print(panel)
There are a large number of options to tweak the pretty formatting, See the Pretty
reference for details.
Rich Repr Protocol
Rich 能够对任何输出进行语法高亮,但格式化只限于内建容器(built-in containers)、dataclasses 和其他 Rich 知道的对象,例如由 attrs 库生成的对象。要将 Rich 的格式化功能添加到自定义对象中,你可以实现 rich repr protocol
Run the following command to see an example of what the Rich repr protocol can generate:
python -m rich.repr
First, let’s look at a class that might benefit from a Rich repr:
class Bird:
def __init__(self, name, eats=None, fly=True, extinct=False):
self.name = name
self.eats = list(eats) if eats else []
self.fly = fly
self.extinct = extinct
def __repr__(self):
return f"Bird({self.name!r}, eats={self.eats!r}, fly={self.fly!r}, extinct={self.extinct!r})"
BIRDS = {
"gull": Bird("gull", eats=["fish", "chips", "ice cream", "sausage rolls"]),
"penguin": Bird("penguin", eats=["fish"], fly=False),
"dodo": Bird("dodo", eats=["fruit"], fly=False, extinct=True)
}
print(BIRDS)
The result of this script would be:
{'gull': Bird('gull', eats=['fish', 'chips', 'ice cream', 'sausage rolls'], fly=True, extinct=False), 'penguin': Bird('penguin', eats=['fish'], fly=False, extinct=False), 'dodo': Bird('dodo', eats=['fruit'], fly=False, extinct=True)}
输出过长,难以阅读。repr 字符串的信息量很大,但有点冗长,因为它们包括默认参数。如果我们用 Rich 来打印,情况就会有一些改善:
{
'gull': Bird('gull', eats=['fish', 'chips', 'ice cream', 'sausage rolls'],
fly=True, extinct=False),
'penguin': Bird('penguin', eats=['fish'], fly=False, extinct=False),
'dodo': Bird('dodo', eats=['fruit'], fly=False, extinct=True)
}