编辑
2024-05-01
CS_杂项
0
请注意,本文编写于 212 天前,最后修改于 212 天前,其中某些信息可能已经过时。

目录

print 功能
Rich Inspect
表格 (Tables)
进度条 (Progress Bar)
Basic Usage
Advanced Usage
树 (Tree)

Rich 是一个 Python 库,可以为您在终端中提供富文本和精美格式。

Rich 的 API 让在终端输出颜色和样式变得很简单。此外,Rich 还可以绘制漂亮的表格、进度条、markdown、语法高亮的源代码以及栈回溯信息(tracebacks)等——开箱即用。

以下所有信息转自:Rich官方markdown

print 功能

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

Rich Inspect

Rich 提供一个 inspect 函数来给任意的 Python 对象打印报告,比如类(class)、实例(instance)和内置对象(builtin)等。

Pyhton
my_list = ["foo", "bar"] from rich import inspect inspect(my_list, methods=True)

rich.inspect(obj, *, console=None, title=None, help=False, methods=False, docs=True, private=False, dunder=False, sort=True, all=False, value=True)

plaintext
Inspect any Python object. - inspect(<OBJECT>) to see summarized info. - inspect(<OBJECT>, methods=True) to see methods. - inspect(<OBJECT>, help=True) to see full (non-abbreviated) help. - inspect(<OBJECT>, private=True) to see private attributes (single underscore). - inspect(<OBJECT>, dunder=True) to see attributes beginning with double underscore. - inspect(<OBJECT>, all=True) to see all attributes. Parameters: - obj (Any) – An object to inspect. - title (str, optional) – Title to display over inspect result, or None use type. Defaults to None. - help (bool, optional) – Show full help text rather than just first paragraph. Defaults to False. - methods (bool, optional) – Enable inspection of callables. Defaults to False. - docs (bool, optional) – Also render doc strings. Defaults to True. - private (bool, optional) – Show private attributes (beginning with underscore). Defaults to False. - dunder (bool, optional) – Show attributes starting with double underscore. Defaults to False. - sort (bool, optional) – Sort attributes alphabetically. Defaults to True. - all (bool, optional) – Show all attributes. Defaults to False. - value (bool, optional) – Pretty print value. Defaults to True. - console (Optional[Console]) – Return type: None

表格 (Tables)

Python
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( "Dec 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)

进度条 (Progress Bar)

用法和tqdm很相似

image.png

Basic Usage

Python
import time from rich.progress import track for i in track(range(20), description="Processing..."): time.sleep(1) # Simulate work being done

Advanced Usage

Python
import time from rich.progress import Progress with Progress() as progress: task1 = progress.add_task("[red]Downloading...", total=1000) task2 = progress.add_task("[green]Processing...", total=1000) task3 = progress.add_task("[cyan]Cooking...", total=1000) while not progress.finished: progress.update(task1, advance=0.5) progress.update(task2, advance=0.3) progress.update(task3, advance=0.9) time.sleep(0.02)

树 (Tree)

Rich 可以渲染一个包含引导线的树(tree)。对于展示文件目录结构和其他分级数据来说,树是理想选择。

树的标签可以是简单文本或任何 Rich 能渲染的东西。执行以下命令查看演示:

Python
""" Demonstrates how to display a tree of files / directories with the Tree renderable. """ import os import pathlib import sys from rich import print from rich.filesize import decimal from rich.markup import escape from rich.text import Text from rich.tree import Tree def walk_directory(directory: pathlib.Path, tree: Tree) -> None: """Recursively build a Tree with directory contents.""" # Sort dirs first then by filename paths = sorted( pathlib.Path(directory).iterdir(), key=lambda path: (path.is_file(), path.name.lower()), ) for path in paths: # Remove hidden files if path.name.startswith("."): continue if path.is_dir(): style = "dim" if path.name.startswith("__") else "" branch = tree.add( f"[bold magenta]:open_file_folder: [link file://{path}]{escape(path.name)}", style=style, guide_style=style, ) walk_directory(path, branch) else: text_filename = Text(path.name, "green") text_filename.highlight_regex(r"\..*$", "bold red") text_filename.stylize(f"link file://{path}") file_size = path.stat().st_size text_filename.append(f" ({decimal(file_size)})", "blue") icon = "🐍 " if path.suffix == ".py" else "📄 " tree.add(Text(icon) + text_filename) try: directory = '' except IndexError: print("[b]Usage:[/] python tree.py <DIRECTORY>") else: tree = Tree( f":open_file_folder: [link file://{directory}]{directory}", guide_style="bold bright_blue", ) walk_directory(pathlib.Path(directory), tree) print(tree)

会产生类似于下面的输出:

本文作者:Geaming

本文链接:

版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!