详细介绍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实现的生成随机迷宫算法核心代码分享(含游戏完整代码)
Jul 11 Python
使用python编写批量卸载手机中安装的android应用脚本
Jul 21 Python
使用Python编写一个在Linux下实现截图分享的脚本的教程
Apr 24 Python
Python cookbook(数据结构与算法)保存最后N个元素的方法
Feb 13 Python
Python实现聊天机器人的示例代码
Jul 09 Python
OpenCV2从摄像头获取帧并写入视频文件的方法
Aug 03 Python
Python 利用scrapy爬虫通过短短50行代码下载整站短视频
Oct 29 Python
对DJango视图(views)和模版(templates)的使用详解
Jul 17 Python
Django使用 Bootstrap 样式修改书籍列表过程解析
Aug 09 Python
Python切图九宫格的实现方法
Oct 10 Python
Python selenium自动化测试模型图解
Apr 15 Python
Django serializer优化类视图的实现示例
Jul 16 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 函数语法介绍一
2009/06/14 PHP
php入门学习知识点二 PHP简单的分页过程与原理
2011/07/14 PHP
yii框架builder、update、delete使用方法
2014/04/30 PHP
php上传图片并压缩的实现方法
2015/12/22 PHP
PHP实现的各类hash算法长度及性能测试实例
2017/08/27 PHP
Laravel 中使用简单的方法跟踪用户是否在线(推荐)
2019/10/30 PHP
SWFObject 2.1以上版本语法介绍
2010/07/10 Javascript
javascript string字符串优化问题
2011/07/31 Javascript
为JavaScript类型增加方法的实现代码(增加功能)
2011/12/29 Javascript
文本域光标操作的jQuery扩展分享
2014/03/10 Javascript
node.js回调函数之阻塞调用与非阻塞调用
2015/11/13 Javascript
基于jQuery实现收缩展开功能
2016/03/18 Javascript
jQuery页面弹出框实现文件上传
2017/02/09 Javascript
vue.js中v-on:textInput无法执行事件问题的解决过程
2017/07/12 Javascript
深入浅析AngularJs模版与v-bind
2018/07/06 Javascript
JavaScript使用小插件实现倒计时的方法讲解
2019/03/11 Javascript
通过实例了解Nodejs模块系统及require机制
2020/07/16 NodeJs
Python实现的几个常用排序算法实例
2014/06/16 Python
python3判断url链接是否为404的方法
2018/08/10 Python
Python 堆叠柱状图绘制方法
2019/07/29 Python
对django2.0 关联表的必填on_delete参数的含义解析
2019/08/09 Python
详解python路径拼接os.path.join()函数的用法
2019/10/09 Python
pytorch实现MNIST手写体识别
2020/02/14 Python
OpenCV中VideoCapture类的使用详解
2020/02/14 Python
Python学习之路之pycharm的第一个项目搭建过程
2020/06/18 Python
css3隔行变换色实现示例
2014/02/19 HTML / CSS
CSS3 text-shadow实现文字阴影效果
2016/02/24 HTML / CSS
详解淘宝H5 sign加密算法
2020/08/25 HTML / CSS
Hertz荷兰:荷兰和全球租车
2018/01/07 全球购物
甜美蛋糕店创业计划书
2014/01/30 职场文书
杭州黄龙洞导游词
2015/02/10 职场文书
教学督导岗位职责
2015/04/10 职场文书
2016春季幼儿园开学寄语
2015/12/03 职场文书
jQuery实现影院选座订座效果
2021/04/13 jQuery
4种非常实用的python内置数据结构
2021/04/28 Python
5种方法告诉你如何使JavaScript 代码库更干净
2021/09/15 Javascript