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


Posted in Python onJuly 31, 2019

前言

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

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

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

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

安装

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

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

pip安装

pip install tqdm

conda安装

conda install -c conda-forge tqdm

迭代对象处理

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

from tqdm import tqdm
import time

for i in tqdm(range(100)):
  time.sleep(0.1)
  pass

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

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

from tqdm import tqdm,trange
import time

for i in trange(100):
  time.sleep(0.1)
  pass

观察处理的数据

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

from tqdm import tqdm
import time

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

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

手动设置处理的进度

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

from tqdm import tqdm
import time

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

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

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

from tqdm import tqdm
import 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 -l
857365

real  0m3.458s
user  0m0.274s
sys   0m3.325s

使用tqdm

$ time find . -name '*.py' -type f -exec cat \{} \; | tqdm | wc -l
857366it [00:03, 246471.31it/s]
857365

real  0m3.585s
user  0m0.862s
sys   0m3.358s

指定tqdm的参数控制进度条

$ find . -name '*.py' -type f -exec cat \{} \; |
  tqdm --unit loc --unit_scale --total 857366 >> /dev/null
100%|???????????????????????????????????| 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.log
100%|????????????????????????????????| 8014/8014 [01:37<00:00, 82.29files/s]

自定义进度条显示信息

通过set_descriptionset_postfix方法设置进度条显示信息

from tqdm import trange
from random import random,randint
import time

with 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)

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

from tqdm import tqdm
import time

with 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()

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

多层循环进度条

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

from tqdm import tqdm
import time

for 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)

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

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

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

多进程进度条

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

from time import sleep
from tqdm import trange, tqdm
from multiprocessing import Pool, freeze_support, RLock

L = 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))

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

pandas中使用tqdm

import pandas as pd
import numpy as np
from tqdm import tqdm

df = pd.DataFrame(np.random.randint(0, 100, (100000, 6)))


tqdm.pandas(desc="my bar!")
df.progress_apply(lambda x: x**2)

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

递归使用进度条

from tqdm import tqdm
import os.path

def 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 files

find_files_recursively("E:/")

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

注意

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

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

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

Python 相关文章推荐
Python编程中运用闭包时所需要注意的一些地方
May 02 Python
浅谈插入排序算法在Python程序中的实现及简单改进
May 04 Python
python dict.get()和dict['key']的区别详解
Jun 30 Python
python使用fcntl模块实现程序加锁功能示例
Jun 23 Python
Python使用pip安装pySerial串口通讯模块
Apr 20 Python
对python cv2批量灰度图片并保存的实例讲解
Nov 09 Python
解决PyCharm的Python.exe已经停止工作的问题
Nov 29 Python
Python3+Pycharm+PyQt5环境搭建步骤图文详解
May 29 Python
python 读写excel文件操作示例【附源码下载】
Jun 19 Python
在python中利用try..except来代替if..else的用法
Dec 19 Python
一文带你了解Python 四种常见基础爬虫方法介绍
Dec 04 Python
python中pyqtgraph知识点总结
Jan 26 Python
处理Selenium3+python3定位鼠标悬停才显示的元素
Jul 31 #Python
基于Django的乐观锁与悲观锁解决订单并发问题详解
Jul 31 #Python
django解决订单并发问题【推荐】
Jul 31 #Python
python opencv将图片转为灰度图的方法示例
Jul 31 #Python
Django中使用极验Geetest滑动验证码过程解析
Jul 31 #Python
Python对接六大主流数据库(只需三步)
Jul 31 #Python
Python爬虫 scrapy框架爬取某招聘网存入mongodb解析
Jul 31 #Python
You might like
深入理解PHP之require/include顺序 推荐
2011/01/02 PHP
php+mysql实现无限分类实例详解
2015/01/15 PHP
php中return的用法实例分析
2015/02/28 PHP
PHP也能干大事之PHP中的编码解码详解
2015/04/20 PHP
PHP页面输出时js设置input框的选中值
2016/09/30 PHP
java解析json方法总结
2019/05/16 PHP
IE浏览器兼容Firefox的JS脚本的代码
2008/10/23 Javascript
基于jQuery的message插件实现右下角弹出消息框
2011/01/11 Javascript
给jQuery方法添加回调函数一款插件的应用
2013/01/21 Javascript
jQuery 鼠标经过(hover)事件的延时处理示例
2014/04/14 Javascript
jQuery实现预加载图片的方法
2015/03/17 Javascript
jquery获得当前html页面源码的方法
2015/07/14 Javascript
Vue2 使用 Echarts 创建图表实例代码
2017/05/18 Javascript
基于AngularJS实现的工资计算器实例
2017/06/16 Javascript
浅谈JavaScript中的属性:如何遍历属性
2017/09/14 Javascript
如何在vue里添加好看的lottie动画
2018/08/02 Javascript
微信小程序云开发如何实现数据库自动备份实现
2019/08/16 Javascript
js tab栏切换代码实例解析
2019/09/03 Javascript
el-table表头根据内容自适应完美解决表头错位和固定列错位
2021/01/07 Javascript
[02:43]DOTA2英雄基础教程 德鲁伊
2014/01/13 DOTA
[14:56]教你分分钟做大人:巫医
2014/10/30 DOTA
pycharm中成功运行图片的配置教程
2018/10/28 Python
浅谈Python的条件判断语句if/else语句
2019/03/21 Python
django 捕获异常和日志系统过程详解
2019/07/18 Python
Python爬虫 scrapy框架爬取某招聘网存入mongodb解析
2019/07/31 Python
python通过安装itchat包实现微信自动回复收到的春节祝福
2020/01/19 Python
Python 读取有公式cell的结果内容实例方法
2020/02/17 Python
python GUI库图形界面开发之PyQt5菜单栏控件QMenuBar的详细使用方法与实例
2020/02/28 Python
Django扫码抽奖平台的配置过程详解
2021/01/14 Python
俄罗斯皮肤健康中心:Pharmacosmetica.ru
2020/02/22 全球购物
Ooni英国官网:披萨烤箱
2020/05/31 全球购物
2014年大学生就业规划书
2014/04/04 职场文书
扬尘污染防治方案
2014/06/15 职场文书
伊琍体标语
2014/06/25 职场文书
2015年体育教学工作总结
2015/05/20 职场文书
导游词之安徽巢湖
2019/12/26 职场文书