使用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代码执行进度的实例代码,希望对大家有所帮助,如果大家有任何疑问欢迎给我留言,小编会及时回复大家的!

相关文章

Django项目中实现使用qq第三方登录功能

Django项目中实现使用qq第三方登录功能

使用qq登录的前提是已经在qq互联官网创建网站应用并获取到QQ互联中网站应用的APP ID和APP KEY 1,建路由 # qq登录 path('loginQq/',qq.log...

在Python中表示一个对象的方法

在 Python 中一切都是对象。如果要在 Python 中表示一个对象,除了定义 class 外还有哪些方式呢?我们今天就来盘点一下。 0x00 dict...

Python基础之getpass模块详细介绍

Python基础之getpass模块详细介绍

本文主要给大家介绍了关于Python中getpass模块的相关内容,分享出来供大家参考学习,话不多说了,来一起看看详细的介绍: getpass模块提供了平台无关的在命令行下输入密码的方法...

实例讲解Python中整数的最大值输出

在Python中可以存储很大的值,如下面的Python示例程序: x = 10000000000000000000000000000000000000000000; x = x...

简单介绍Python中的JSON使用

JSON进阶 Python的dict对象可以直接序列化为JSON的{},不过,很多时候,我们更喜欢用class表示对象,比如定义Student类,然后序列化: import json...