Rich

使用 Rich API 可以很容易的在终端输出添加各种颜色和不同风格。它可以绘制漂亮的表格,进度条,markdown,突出显示语法的源代码及回溯等等
文档地址:https://rich.readthedocs.io/en/latest

替代原生 print

from rich import print
print("Hello, [bold magenta]World[/bold magenta]!")

自定义 Console 控制台输出

from rich.console import Console
console = Console()
console.print("Hello", "World!")
console.print("Hello", "World!", style="bold red") # 指定了整行文字的样式
console.print("Where there is a [bold cyan]Will[/bold cyan] there [u]is[/u] a [i]way[/i].") # 分段样式
console.print(":smiley: :vampire: :pile_of_poo: :thumbs_up: :raccoon:") # 将名称放在两个冒号之间即可在控制台输出中插入表情符号

请注意,与内置的“打印”功能不同,Rich 会将文字自动换行以适合终端宽度

Console.log

该方法具有与 print() 类似的界面,除此之外,还能显示当前时间以及被调用的文件和行

log 方法既可用于将长时间运行应用程序(例如服务器)的日志记录到终端,也可用于辅助调试。

还可以使用内置的处理类来对 Rich 日志记录模块的输出进行格式化和着色:

Pasted image 20240301072941.png

表格

from rich.console import Console
from rich.table import Column, Table

console = Console()
table = Table(show_header=True, header_style="bold magenta")

##############################################################

table.add_column("Date", style="dim", width=12)
table.add_column("Title")
table.add_column("Production Budget", justify="right")
table.add_column("Box Office", justify="right")
table.add_row(
    "Dev 20, 2019", "Star Wars: The Rise of Skywalker", "$275,000,000", "$375,126,118"
)
table.add_row(
    "May 25, 2018",
    "[red]Solo[/red]: A Star Wars Story",
    "$275,000,000",
    "$393,151,347",
)
table.add_row(
    "Dec 15, 2017",
    "Star Wars Ep. VIII: The Last Jedi",
    "$262,000,000",
    "[bold]$1,332,539,889[/bold]",
)

console.print(table)

请注意,控制台标记的呈现方式与 print() 和 log() 相同。实际上,由 Rich 渲染的任何内容都可以添加到标题/行(甚至其他表格)中。

输出结果:

Pasted image 20240301073203.png

Table 类很聪明,可以调整列的大小以适合终端的可用宽度,并能根据需要做文本环绕的处理。

进度条

from rich.progress import track

for step in track(range(100)):
    do_step(step)

按列输出数据

Rich 可以将内容通过排列整齐的,具有相等或最佳的宽度的列来呈现。下面是 ls 命令的一个非常基本的克隆,用列来显示目录列表:

import os
import sys

from rich import print
from rich.columns import Columns

directory = os.listdir(sys.argv[1])
print(Columns(directory))

Pasted image 20240301073521.png

Markdown

from rich.console import Console
from rich.markdown import Markdown

console = Console()
with open("README.md") as readme:
    markdown = Markdown(readme.read())
console.print(markdown)

语法高亮

使用方法:syntax = Syntax(my_code, "python", theme="monokai", line_numbers=True)

例子:

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)

错误回溯 traceback

比 python 自带的 traceback 更丰富、易读

Pasted image 20240301073717.png

https://zhuanlan.zhihu.com/p/394105084