分享

假如有一个专属于python的终端工具,那绝对非他莫属!

 Python集中营 2023-02-03 发布于甘肃

rich是python中的一个非标准模块,它提供了比较漂亮的富文本和不同风格的控制台支持。

它能够在控制台中绘制出精美的数据表格/进度条以及突出语法的显示等效果,重要的是还能结合notebook的使用方便科学计算的开发。

rich作为python的非标准库,我们在使用前需要使用pip的方式安装一下。

pip install rich

安装完成之后,我们可以在操作系统的终端看看rich模块的效果非常的漂亮。

python -m rich

在做一些业务代码开发的时候,我们可以将rich模块导入进来使用它的print函数来完成对控制台的打印。

# It's importing the `print` function from the `rich` module.
from rich import print

# It's printing a string with bold magenta text.
print('[bold magenta]我是一个rich的终端打印![/bold magenta]')

可以发现,我们在使用rich模块的打印print函数加上[bold magenta][/bold magenta]之后打印出来的效果是经过了个性化的处理的。

注意:rich模块这样的效果必须是在操作系统的终端下面才能显示出来,在开发工具比如说pycharm中就显示不出来的。

接下来,我们来说明常见的两个业务场景中的显示如何开发,分别是在控制台显示表格和进度条。

因为在一般的日志打印中表格的打印能够帮助我们很好的观察程序执行过程中的数据,这里着重说明一下。

# It's importing the `Console` class from the `rich.console` module.
from rich.console import Console

# It's importing the `Column` and `Table` classes from the `rich.table` module.
from rich.table import Table

# 导入相应的模块之后,我们需要初始化Console的控制台对象用作后面的print函数打印。

# It's creating a Console object.
console = Console()

初始化rich模块的表格对象Table,并且向表对象中加入相应的表字段和行数据来查看效果。

# It's creating a Table object with a header and a bold magenta header style.
tab_ = Table(show_header=True, header_style="bold magenta")

# It's adding a column named "姓名" with a dim style and a width of 12.
tab_.add_column("姓名")

# It's adding a column named "年龄" with a default style and a default width.
tab_.add_column("年龄")

# It's adding a column named "班级" with a default style and a default width.
tab_.add_column("班级")

# It's adding a column named "成绩" with a default style and a default width.
tab_.add_column("成绩")

# It's adding a row to the table.
tab_.add_row("Python 集中营""21""1210班""99.5")

# It's adding a row to the table.
tab_.add_row("Python 集中营""21""1210班""99.5")

# It's adding a row to the table.
tab_.add_row("Python 集中营""21""1210班""99.5")

# It's adding a row to the table.
tab_.add_row("Python 集中营""21""1210班""99.5")

# It's printing the table to the console.
console.print(tab_)

我们将表格打印的这部分代码块放到了test8_test.py的python文件,然后到控制台的终端去执行观察一下结果。

python -m test8_test.py

下面来看看rich模块的进度条是如何使用的,同样的我们做一个读取文件的进度显示比较符合实际业务开发的情况。

import rich.progress

with rich.progress.open("data.txt""rb", description="文件读取过程:"as file:
    results = file.readlines()

# 文件读取过程: ---------------------------------------- 2.1/2.1 kB 0:00:00

「Python 集中营」,只做知识分享 !

就是玩儿:python轻松实现代码雨效果!

python情感分析:基于jieba的分词及snownlp的情感分析!

python数据保存:记录pandas数据分析完成后的轻量级数据保存!

记录一次关于python内存泄露的排查!

    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多