1. 安装
pip install rich
Collecting rich
Downloading rich-13.6.0-py3-none-any.whl.metadata (18 kB)
Collecting markdown-it-py>=2.2.0 (from rich)
Downloading markdown_it_py-3.0.0-py3-none-any.whl.metadata (6.9 kB)
Collecting pygments<3.0.0,>=2.13.0 (from rich)
Downloading Pygments-2.16.1-py3-none-any.whl.metadata (2.5 kB)
Collecting mdurl~=0.1 (from markdown-it-py>=2.2.0->rich)
Downloading mdurl-0.1.2-py3-none-any.whl (10.0 kB)
Downloading rich-13.6.0-py3-none-any.whl (239 kB)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 239.8/239.8 kB 59.9 kB/s eta 0:00:00
Downloading markdown_it_py-3.0.0-py3-none-any.whl (87 kB)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 87.5/87.5 kB 121.7 kB/s eta 0:00:00
Downloading Pygments-2.16.1-py3-none-any.whl (1.2 MB)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 1.2/1.2 MB 54.3 kB/s eta 0:00:00
Installing collected packages: pygments, mdurl, markdown-it-py, rich
Successfully installed markdown-it-py-3.0.0 mdurl-0.1.2 pygments-2.16.1 rich-13.6.0
2. 进度条
from rich.progress import track
import time
for step in track(range(30), description='Processing...'):
print('hello rich')
time.sleep(0.5)
展示效果:
3. console控制台
为了完全控制终端格式,Rich提供了一个Console类。
from rich.console import Console
console = Console()
在构建Console对象时,你可以选择以下参数:
- size 是终端的当前尺寸(尽量不要手动设置它,因为它是自动的)
- encoding 编码方式
- color_system 颜色空间
- file 当你设置了这个参数,Console的打印将被重定向到指定文件
3.1 使用console.rule()来打印带标题的分隔线
from rich.console import Console
console = Console()
console.print('hellllllo world')
console.rule("[bold red]Chapter 2")
console.print('may the god be with you')
console.print('gigigaga')
3.2 使用console.log()来打印日志
console.log('hello world')
输出:
[19:51:28] hello world
4. 表单
rich.table.Table()
的实例为一个具有行和列的可渲染对象
from rich.table import Table
from rich.console import Console
console = Console()
table = Table()
table.add_column('[red]test')
table.add_column('[red]test2')
table.add_row('[red]this is a table', '[yellow]this is a table')
table.add_row('[red]hello', '[yellow]world')
console.print(table)
输出