详细介绍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 相关文章推荐
python3利用smtplib通过qq邮箱发送邮件方法示例
Dec 03 Python
Python实现简单的语音识别系统
Dec 13 Python
Python smtplib实现发送邮件功能
May 22 Python
pandas 透视表中文字段排序方法
Nov 16 Python
python把1变成01的步骤总结
Feb 27 Python
python内存监控工具memory_profiler和guppy的用法详解
Jul 29 Python
简单了解django orm中介模型
Jul 30 Python
Django中自定义查询对象的具体使用
Oct 13 Python
Python socket连接中的粘包、精确传输问题实例分析
Mar 24 Python
keras小技巧——获取某一个网络层的输出方式
May 23 Python
Django REST 异常处理详解
Jul 15 Python
详解python中的lambda与sorted函数
Sep 04 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可变函数的使用详解
2013/06/14 PHP
Laravel 对某一列进行筛选然后求和sum()的例子
2019/10/10 PHP
jqPlot jquery的页面图表绘制工具
2009/07/25 Javascript
一步一步制作jquery插件Tabs实现过程
2010/07/06 Javascript
javascript数组操作方法小结和3个属性详细介绍
2014/07/05 Javascript
jQuery控制Div拖拽效果完整实例分析
2015/04/15 Javascript
jQuery基于json与cookie实现购物车的方法
2016/04/15 Javascript
jQuery Layer弹出层传值到父页面的实现代码
2017/08/17 jQuery
Django中使用jquery的ajax进行数据交互的实例代码
2017/10/15 jQuery
Vue.js 实现微信公众号菜单编辑器功能(一)
2018/05/08 Javascript
JavaScript实现动态添加、移除元素或属性的方法分析
2019/01/03 Javascript
实用的Vue开发技巧
2019/05/30 Javascript
使用Vue CLI创建typescript项目的方法
2019/08/09 Javascript
mui js控制开关状态、修改switch开关的值方法
2019/09/03 Javascript
es6中reduce的基本使用方法
2019/09/10 Javascript
layer iframe 设置关闭按钮的方法
2019/09/12 Javascript
[02:56]《DAC最前线》之国外战队抵达上海备战亚洲邀请赛
2015/01/28 DOTA
vc6编写python扩展的方法分享
2014/01/17 Python
Python实现选择排序
2017/06/04 Python
python生成excel的实例代码
2017/11/08 Python
sublime python3 输入换行不结束的方法
2018/04/19 Python
python能做哪些生活有趣的事情
2020/09/09 Python
Python join()函数原理及使用方法
2020/11/14 Python
详解Django中的FBV和CBV对比分析
2021/03/01 Python
css3 transform属性详解
2014/09/30 HTML / CSS
CSS3实现内凹圆角的实例代码
2017/05/04 HTML / CSS
html5中的一些标签学习(心得)
2016/10/18 HTML / CSS
国际鲜花速递专家:Floraqueen
2016/11/24 全球购物
世界领先的高品质定制产品平台:Zazzle
2017/07/23 全球购物
构造方法和其他方法的区别
2016/04/26 面试题
班组长的岗位职责
2013/12/09 职场文书
领导干部培训感言
2014/01/23 职场文书
2014年教师节寄语
2014/04/03 职场文书
迎国庆演讲稿
2014/09/15 职场文书
物业工程部主管岗位职责
2015/04/16 职场文书
看古人们是如何赞美老师的?
2019/07/08 职场文书