神剑山庄资源网 Design By www.hcban.com
在使用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代码执行进度的实例代码,希望对大家有所帮助,如果大家有任何疑问欢迎给我留言,小编会及时回复大家的!
神剑山庄资源网 Design By www.hcban.com
神剑山庄资源网
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件!
如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
神剑山庄资源网 Design By www.hcban.com
暂无使用tqdm显示Python代码执行进度功能的评论...
更新日志
2024年09月30日
2024年09月30日
- 孙悦.1996-伙伴【正大国际】【WAV+CUE】
- 纪钧瀚《钢琴阅读时光 雨中书店聆听轻音乐》[FLAC/分轨][399.62MB]
- 证声音乐图书馆《走向自然 疗心爵士乐》[320K/MP3][87.4MB]
- 证声音乐图书馆《走向自然 疗心爵士乐》[FLAC/分轨][184.94MB]
- 陈慧娴.2018-Priscilla-Ism演唱会3CD(2024环球红馆40复刻系列)【环球】【WAV+CUE】
- 郑秀文.1999-我应该得到(国)【华纳】【WAV+CUE】
- 陈家慧.2011-钢琴酒吧2CD【龙吟唱片】【WAV+CUE】
- 证声音乐图书馆《雨季 蓝调吉他 Rainy Blues》[320K/MP3][45.01MB]
- 证声音乐图书馆《雨季 蓝调吉他 Rainy Blues》[FLAC/分轨][109.13MB]
- 赞多《序章》[320K/MP3][45.54MB]
- 许巍.2004-每一刻都是崭新的【步升大风】【WAV+CUE】
- 群星.2024-四方馆影视原声带【韶愔音乐】【FLAC分轨】
- 陈雷.1997-安锁咧【金圆唱片】【WAV+CUE】
- 关淑怡.2013-MY.FAVORITE.SK.3CD【环球】【WAV+CUE】
- Sweety.2006-花言乔语【丰华】【WAV+CUE】