使用tqdm显示Python代码执行进度功能

yipeiwu_com7年前Python基础

在使用Python执行一些比较耗时的操作时,为了方便观察进度,通常使用进度条的方式来可视化呈现。Python中的tqdm就是用来实现此功能的。

先来看看tqdm的进度条效果:

 

tqdm的基本用法

tqdm最主要的用法有3种,自动控制、手动控制或者用于脚本或命令行。

自动控制运行

最基本的用法,将tqdm()直接包装在任意迭代器上。

from tqdm import tqdm
import time
text = ""
for char in tqdm(["a", "b", "c", "d"]):
 text = text + char
 time.sleep(0.5)

trange(i) 是对tqdm(range(i)) 特殊优化过的实例:

from tqdm import trange
import time
for i in trange(100):
 time.sleep(0.1)

如果在循环之外实例化,可以允许对tqdm() 手动控制:

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

手动控制运行

用with 语句手动控制 tqdm() 的更新:

from tqdm import tqdm
import time
with tqdm(total=100) as pbar:
 for i in range(10):
  pbar.update(10)
  time.sleep(0.5)

或者不用with语句,但是最后需要加上del或者close()方法:

from tqdm import tqdm
import time
pbar = tqdm(total=100)
for i in range(10):
 pbar.update(10)
 time.sleep(0.5)
pbar.close()

tqdm.update()方法用于手动更新进度条,对读取文件之类的流操作非常有用:

tqdm在多进程场景下的应用

代码示例:

from multiprocessing import Pool

import tqdm
import time
def _foo(my_number):
 square = my_number * my_number
 time.sleep(1)
 return square 
if __name__ == '__main__':
 with Pool(2) as p:
  r = list(tqdm.tqdm(p.imap(_foo, range(30)), total=30))

参考链接:

https://github.com/tqdm/tqdm

总结

以上所述是小编给大家介绍的使用tqdm显示Python代码执行进度的实例代码,希望对大家有所帮助,如果大家有任何疑问欢迎给我留言,小编会及时回复大家的!

相关文章

简单介绍Python中的filter和lambda函数的使用

filter(function or None, sequence),其中sequence 可以是list ,tuple,string。这个函数的功能是过滤出sequence 中所有以元...

python如何定义带参数的装饰器

本文实例为大家分享了python定义带参数装饰器的具体代码,供大家参考,具体内容如下 案例:        实现一个装饰器,用...

Python何时应该使用Lambda函数

Python 中定义函数有两种方法,一种是用常规方式 def 定义,函数要指定名字,第二种是用 lambda 定义,不需要指定名字,称为 Lambda 函数。 Lambda 函数又称匿名...

Python3匿名函数用法示例

本文实例讲述了Python3匿名函数用法。分享给大家供大家参考,具体如下: # -*- coding:utf-8 -*- #!python3 # 匿名函数 # 1.不用给函数取名 #...

替换python字典中的key值方法

比如有一个 a = {‘a': 1} 希望变为 a = {‘b' :1} 即:在保留value不变的情况下,替换key值 目前能想到的实现方案是 a[‘b'] = a.p...