python任务进度实时显示_Python 进度条模块显示-tqdm | 文艺数学君

摘要这一篇主要介绍一个 Python 的库,tqdm,可以可视化 loop 的过程。

简介

在使用 Python 写循环的时候,对于一些比较长的步骤,我们希望可以实时显示一个进度条,让我看可以看到目前的进展。于是,tqdm 这个库就可以帮助我们实现这个进度条(Instantly make your loops show a smart progress meter - just wrap any iterable with tqdm(iterable), and you're done!)。

这一篇会简单介绍一下 tqdm 这个库的使用,可以在循环的时候加上进度条,也可以在读取文件的时候加上进度条。关于 tqdm的参考资料,可以直接看他的 Github 的仓库链接,Github-tqdm。

tqdm 使用介绍

可视化循环

我们只需要在循环外面加上 tqdm,即可对 loop 进行可视化。

import tqdm

for i in tqdm.tqdm(range(1000)):

pass

运行上面的代码,我们可以得到下面的可视化的效果:

20201026_145423_sk4rt3u.jpg

我们可以对上面的 tqdm 进行一些设置,下面是两个常见的设置:

ncols : The width of the entire output message. If specified, dynamically resizes the progressbar to stay within this bound. If unspecified, attempts to use environment width. The fallback is a meter width of 10 and no limit for the counter and statistics. If 0, will not print any meter (only stats). => 设置显示的长度

ascii : If unspecified or False, use unicode (smooth blocks) to fill the meter. The fallback is to use ASCII characters " 123456789#". => 设置填充的内容

读取文件过程的可视化

我们在对一些大文件进行操作的时候,同样可以使用 tqdm 来进行可视化。我们首先获得该文件总的大小,接着实时更新每一次文件处理的位置即可,下面是一个可视化文件处理过程的例子:

with tqdm.tqdm(total = os.path.getsize(file_name)) as pbar:

with open(file_name, 'r') as f:

for line in f:

pbar.update(len(line)) # 显示文件处理的进度

pass

20201026_150145_49dxs62.jpg

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值