侯体宗的博客
  • 首页
  • Hyperf版
  • beego仿版
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

详细介绍Python进度条tqdm的使用

Python  /  管理员 发布于 7年前   287

前言

有时候在使用Python处理比较耗时操作的时候,为了便于观察处理进度,这时候就需要通过进度条将处理情况进行可视化展示,以便我们能够及时了解情况。这对于第三方库非常丰富的Python来说,想要实现这一功能并不是什么难事。

tqdm就能非常完美的支持和解决这些问题,可以实时输出处理进度而且占用的CPU资源非常少,支持windows、Linux、mac等系统,支持循环处理、多进程、递归处理、还可以结合linux的命令来查看处理情况,等进度展示。

大家先看看tqdm的进度条效果

安装

github地址:https://github.com/tqdm/tqdm

想要安装tqdm也是非常简单的,通过pip或conda就可以安装,而且不需要安装其他的依赖库

pip安装

pip install tqdm

conda安装

conda install -c conda-forge tqdm

迭代对象处理

对于可以迭代的对象都可以使用下面这种方式,来实现可视化进度,非常方便

from tqdm import tqdmimport timefor i in tqdm(range(100)):  time.sleep(0.1)  pass


在使用tqdm的时候,可以将tqdm(range(100))替换为trange(100)代码如下

from tqdm import tqdm,trangeimport timefor i in trange(100):  time.sleep(0.1)  pass

观察处理的数据

通过tqdm提供的set_description方法可以实时查看每次处理的数据

from tqdm import tqdmimport timepbar = tqdm(["a","b","c","d"])for c in pbar:  time.sleep(1)  pbar.set_description("Processing %s"%c)

手动设置处理的进度

通过update方法可以控制每次进度条更新的进度

from tqdm import tqdmimport time#total参数设置进度条的总长度with tqdm(total=100) as pbar:  for i in range(100):    time.sleep(0.05)    #每次更新进度条的长度    pbar.update(1)


除了使用with之外,还可以使用另外一种方法实现上面的效果

from tqdm import tqdmimport time#total参数设置进度条的总长度pbar = tqdm(total=100)for i in range(100):  time.sleep(0.05)  #每次更新进度条的长度  pbar.update(1)#关闭占用的资源pbar.close()

linux命令展示进度条

不使用tqdm

$ time find . -name '*.py' -type f -exec cat \{} \; | wc -l857365real  0m3.458suser  0m0.274ssys   0m3.325s

使用tqdm

$ time find . -name '*.py' -type f -exec cat \{} \; | tqdm | wc -l857366it [00:03, 246471.31it/s]857365real  0m3.585suser  0m0.862ssys   0m3.358s

指定tqdm的参数控制进度条

$ find . -name '*.py' -type f -exec cat \{} \; |  tqdm --unit loc --unit_scale --total 857366 >> /dev/null100%|| 857K/857K [00:04<00:00, 246Kloc/s]
$ 7z a -bd -r backup.7z docs/ | grep Compressing |  tqdm --total $(find docs/ -type f | wc -l) --unit files >> backup.log100%|| 8014/8014 [01:37<00:00, 82.29files/s]

自定义进度条显示信息

通过set_description和set_postfix方法设置进度条显示信息

from tqdm import trangefrom random import random,randintimport timewith trange(100) as t:  for i in t:    #设置进度条左边显示的信息    t.set_description("GEN %i"%i)    #设置进度条右边显示的信息    t.set_postfix(loss=random(),gen=randint(1,999),str="h",lst=[1,2])    time.sleep(0.1)

from tqdm import tqdmimport timewith tqdm(total=10,bar_format="{postfix[0]}{postfix[1][value]:>9.3g}",     postfix=["Batch",dict(value=0)]) as t:  for i in range(10):    time.sleep(0.05)    t.postfix[1]["value"] = i / 2    t.update()

多层循环进度条

通过tqdm也可以很简单的实现嵌套循环进度条的展示

from tqdm import tqdmimport timefor i in tqdm(range(20), ascii=True,desc="1st loop"):  for j in tqdm(range(10), ascii=True,desc="2nd loop"):    time.sleep(0.01)


在pycharm中执行以上代码的时候,会出现进度条位置错乱,目前官方并没有给出好的解决方案,这是由于pycharm不支持某些字符导致的,不过可以将上面的代码保存为脚本然后在命令行中执行,效果如下

多进程进度条

在使用多进程处理任务的时候,通过tqdm可以实时查看每一个进程任务的处理情况

from time import sleepfrom tqdm import trange, tqdmfrom multiprocessing import Pool, freeze_support, RLockL = list(range(9))def progresser(n):  interval = 0.001 / (n + 2)  total = 5000  text = "#{}, est. {:<04.2}s".format(n, interval * total)  for i in trange(total, desc=text, position=n,ascii=True):    sleep(interval)if __name__ == '__main__':  freeze_support() # for Windows support  p = Pool(len(L),       # again, for Windows support       initializer=tqdm.set_lock, initargs=(RLock(),))  p.map(progresser, L)  print("\n" * (len(L) - 2))

pandas中使用tqdm

import pandas as pdimport numpy as npfrom tqdm import tqdmdf = pd.DataFrame(np.random.randint(0, 100, (100000, 6)))tqdm.pandas(desc="my bar!")df.progress_apply(lambda x: x**2)

递归使用进度条

from tqdm import tqdmimport os.pathdef find_files_recursively(path, show_progress=True):  files = []  # total=1 assumes `path` is a file  t = tqdm(total=1, unit="file", disable=not show_progress)  if not os.path.exists(path):    raise IOError("Cannot find:" + path)  def append_found_file(f):    files.append(f)    t.update()  def list_found_dir(path):    """returns os.listdir(path) assuming os.path.isdir(path)"""    try:      listing = os.listdir(path)    except:      return []    # subtract 1 since a "file" we found was actually this directory    t.total += len(listing) - 1    # fancy way to give info without forcing a refresh    t.set_postfix(dir=path[-10:], refresh=False)    t.update(0) # may trigger a refresh    return listing  def recursively_search(path):    if os.path.isdir(path):      for f in list_found_dir(path):        recursively_search(os.path.join(path, f))    else:      append_found_file(path)  recursively_search(path)  t.set_postfix(dir=path)  t.close()  return filesfind_files_recursively("E:/")

注意

在使用tqdm显示进度条的时候,如果代码中存在print可能会导致输出多行进度条,此时可以将print语句改为tqdm.write,代码如下

for i in tqdm(range(10),ascii=True):  tqdm.write("come on")  time.sleep(0.1)

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。


  • 上一条:
    python Matplotlib底图中鼠标滑过显示隐藏内容的实例代码
    下一条:
    处理Selenium3+python3定位鼠标悬停才显示的元素
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • 在python语言中Flask框架的学习及简单功能示例(0个评论)
    • 在Python语言中实现GUI全屏倒计时代码示例(0个评论)
    • Python + zipfile库实现zip文件解压自动化脚本示例(0个评论)
    • python爬虫BeautifulSoup快速抓取网站图片(1个评论)
    • vscode 配置 python3开发环境的方法(0个评论)
    • 近期文章
    • 智能合约Solidity学习CryptoZombie第四课:僵尸作战系统(0个评论)
    • 智能合约Solidity学习CryptoZombie第三课:组建僵尸军队(高级Solidity理论)(0个评论)
    • 智能合约Solidity学习CryptoZombie第二课:让你的僵尸猎食(0个评论)
    • 智能合约Solidity学习CryptoZombie第一课:生成一只你的僵尸(0个评论)
    • 在go中实现一个常用的先进先出的缓存淘汰算法示例代码(0个评论)
    • 在go+gin中使用"github.com/skip2/go-qrcode"实现url转二维码功能(0个评论)
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(0个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 欧盟关于强迫劳动的规定的官方举报渠道及官方举报网站(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2016-10
    • 2016-11
    • 2018-04
    • 2020-03
    • 2020-04
    • 2020-05
    • 2020-06
    • 2022-01
    • 2023-07
    • 2023-10
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客