Python终端美化——rich

简介: Python终端美化——rich

rich简介

rich是一个用于美化终端的Python库,下面这幅图展示了它的主要功能。

rich的文档提供了详细的说明:

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


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


安装:

python -m pip install rich

预览:

在终端运行python -m rich,可以看到图2的效果。

rich常用功能

下面根据How to Use the Rich Library with Python,介绍一下rich的常用功能。

1. 替代print

可以使用richprint函数替代内置的print

from rich import print

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


2. 在交互命令行(REPL)使用

>>> from rich import pretty
>>> pretty.install()

>>> locals()

3. 控制终端格式

为了完全控制终端格式,Rich 提供了一个 Console 类。

from rich.console import Console

console = Console()

def merge_dict(dict_one, dict_two):
    merged_dict = dict_one | dict_two
    console.log(merged_dict, log_locals=True)

merge_dict({'id': 1}, {'name': 'Ashutosh'})

我们创建了一个Console对象,然后使用log方法打印了一个合并后的字典。log方法和print方法类似,但是添加了一些帮助调试的信息,例如我们用log_locals打印局部变量。

Console提供了很多功能,如控制终端的颜色、样式、大小以及输出不同内容。详细的说明可以参考Console API

4. 使用inspect检查对象

from rich import inspect
import rich

inspect(rich)

5. 使用Tree显示文件系统等树状结构

from rich.tree import Tree
from rich import print as rprint


tree = Tree("Family Tree")
tree.add("Mom")
tree.add("Dad")
tree.add("Brother").add("Wife")
tree.add("[red]Sister").add("[green]Husband").add("[blue]Son")

rprint(tree)

6. 显示进度条

from rich.progress import track
from time import sleep

def process_data():
    sleep(0.02)

for _ in track(range(100), description='[green]Processing data'):
    process_data()


如果我们想记录特定任务完成执行的时间,我们可以用console.status

from rich.console import Console
from time import sleep

console = Console()

data = [1, 2, 3, 4, 5]
with console.status("[bold green]Fetching data...") as status:
    while data:
        num = data.pop(0)
        sleep(1)
        console.log(f"[green]Finish fetching data[/green] {num}")

    console.log(f'[bold][red]Done!')

如果需要在显示中执行多个任务或想要自定义进度显示中的列,则可以直接使用 Progress 类。创建 Progress 对象后,使用add_task() 添加任务,使用 update_progress()更新进度。

import time

from rich.progress import Progress

with Progress() as progress:

    task1 = progress.add_task("[red]Downloading...", total=100)
    task2 = progress.add_task("[green]Processing...", total=100)
    task3 = progress.add_task("[cyan]Installing...", total=100)

    while not progress.finished:
        progress.update(task1, advance=0.9)
        progress.update(task2, advance=0.6)
        progress.update(task3, advance=0.3)
        time.sleep(0.02)

Progress 类旨在用作上下文管理器,自动启动和停止进度显示。

7. 显示列

Rich 可以将文本(或其他Rich renderables对象)呈现 Columns中。

import json
from urllib.request import urlopen

from rich.console import Console
from rich.columns import Columns
from rich.panel import Panel

def get_content(user):
    """Extract text from user dict."""
    country = user["location"]["country"]
    name = f"{user['name']['first']} {user['name']['last']}"
    return f"[b]{name}[/b]\n[yellow]{country}"

console = Console()

users = json.loads(urlopen("https://randomuser.me/api/?results=30").read())["results"]
user_renderables = [Panel(get_content(user), expand=True) for user in users]
console.print(Columns(user_renderables))

8. 显示表格

Rich的Table类提供了多种将表格数据呈现到终端的方法。Table类具有 add_column()add_row()方法,用于将列和行分别添加到Table中。

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

table = Table(title="Todo List")

table.add_column("S. No.", style="cyan", no_wrap=True)
table.add_column("Task", style="magenta")
table.add_column("Status", justify="right", style="green")

table.add_row("1", "Buy Milk", "✅")
table.add_row("2", "Buy Bread", "✅")
table.add_row("3", "Buy Jam", "❌")

console = Console()
console.print(table)


相关文章
|
1月前
|
缓存 Unix C语言
涨见识了,在终端执行 Python 代码的 6 种方式!
涨见识了,在终端执行 Python 代码的 6 种方式!
58 0
|
1月前
|
Shell Python
[oeasy]python0003_ 终端大冒险_终端命令_whoami_pwd_ls
[oeasy]python0003_ 终端大冒险_终端命令_whoami_pwd_ls
42 5
|
存储 Shell Linux
安卓手机上的终端模拟器Termux,实现了在手机上运行python
安卓手机上的终端模拟器Termux,可以在手机上运行python
1532 2
|
1月前
|
Shell 测试技术 Python
在Mac上用Python调用终端执行命令
在Mac上用Python调用终端执行命令
44 1
|
1月前
|
Python
2024年最全用Python和PIL美化图像:文本覆盖技术实战,Python高级面试题pdf
2024年最全用Python和PIL美化图像:文本覆盖技术实战,Python高级面试题pdf
|
10月前
|
索引 Python
Python的知识点运用-3(不太基础的基础运用,代码美化)
Python的知识点运用-3(不太基础的基础运用,代码美化)
45 0
|
9月前
|
SQL 前端开发 Java
python之input()函数的使用——在终端输入想要的值,小白也能学会的python之路
python之input()函数的使用——在终端输入想要的值,小白也能学会的python之路
|
8月前
|
Linux 网络安全 Python
百度搜索:蓝易云【如何在Centos的SSH2终端中终止-停止-结束某个Python程序的运行?】
这些方法可以帮助你在CentOS的SSH终端中终止、停止或结束某个Python程序的运行。选择适合你情况的方法,并根据需要使用相应的命令来终止运行中的程序。请注意,终止程序可能会导致未保存的数据丢失,所以在操作之前确保已保存必要的数据。
115 0
|
数据可视化 Unix
[oeasy]python0086_ASCII_出现背景_1963年_DEC_PDP系列主机_VT系列终端
[oeasy]python0086_ASCII_出现背景_1963年_DEC_PDP系列主机_VT系列终端
154 0
[oeasy]python0086_ASCII_出现背景_1963年_DEC_PDP系列主机_VT系列终端
|
Unix
[oeasy]python0081_ANSI序列由来_终端机_VT100_DEC_VT选项_终端控制序列
[oeasy]python0081_ANSI序列由来_终端机_VT100_DEC_VT选项_终端控制序列
60 0
[oeasy]python0081_ANSI序列由来_终端机_VT100_DEC_VT选项_终端控制序列