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)


相关文章
|
5月前
|
缓存 Unix C语言
涨见识了,在终端执行 Python 代码的 6 种方式!
涨见识了,在终端执行 Python 代码的 6 种方式!
163 0
|
5月前
|
Shell Python
[oeasy]python0003_ 终端大冒险_终端命令_whoami_pwd_ls
[oeasy]python0003_ 终端大冒险_终端命令_whoami_pwd_ls
73 5
|
10天前
|
Python
在python终端中打印颜色的3中方式(python3经典编程案例)
这篇文章介绍了在Python终端中打印彩色文本的三种方式:使用`colorama`模块、`termcolor`模块和ANSI转义码。
26 8
|
3月前
|
Linux Python Windows
在终端怎么升级python
Windows上,使用`Win+R`打开命令行,运行`cmd`,然后用`python -m ensurepip --upgrade`更新pip。通常需从官网下载安装新版本Python。验证版本用`python --version`。 Mac/Linux,打开终端,用`conda update python`(Anaconda/Miniconda环境)或手动下载安装新版本。 验证版本:`python3 --version`或`python --version`。
64 9
|
2月前
|
IDE Linux 开发工具
涨见识了,在终端执行 Python 代码的 6 种方式!
涨见识了,在终端执行 Python 代码的 6 种方式!
28 0
|
4月前
|
Python
利用Python控制终端打印字体的颜色和格式
利用Python控制终端打印字体的颜色和格式
57 2
|
5月前
|
Shell 测试技术 Python
在Mac上用Python调用终端执行命令
在Mac上用Python调用终端执行命令
203 1
|
5月前
|
Python
2024年最全用Python和PIL美化图像:文本覆盖技术实战,Python高级面试题pdf
2024年最全用Python和PIL美化图像:文本覆盖技术实战,Python高级面试题pdf
|
缓存 Unix Shell
在终端执行 Python 代码的 6 种方式!
在终端执行 Python 代码的 6 种方式!
525 0
下一篇
无影云桌面