【转】Python进度条tqdm的使用
有时候在使用Python处理比较耗时操作的时候,为了便于观察处理进度,这时候就需要通过进度条将处理情况进行可视化展示,以便我们能够及时了解情况。这对于第三方库非常丰富的Python来说,想要实现这一功能并不是什么难事。
tqdm就能非常完美的支持和解决这些问题,可以实时输出处理进度而且占用的CPU资源非常少,支持windows、Linux、mac等系统,支持循环处理、多进程、递归处理、还可以结合linux的命令来查看处理情况,等进度展示。
安装
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
在使用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)
手动设置处理的进度
通过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)
除了使用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_description和set_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)
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()
多层循环进度条
通过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)
在pycharm中执行以上代码的时候,会出现进度条位置错乱,目前官方并没有给出好的解决方案,这是由于pycharm不支持某些字符导致的,不过可以将上面的代码保存为脚本然后在命令行中执行,效果如下
多进程进度条
在使用多进程处理任务的时候,通过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))
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)
递归使用进度条
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:/")
注意
在使用tqdm显示进度条的时候,如果代码中存在print可能会导致输出多行进度条,此时可以将print语句改为tqdm.write,代码如下
for i in tqdm(range(10),ascii=True):
tqdm.write("come on")
time.sleep(0.1)
参考:
https://www.jb51.net/article/166648.htm
【转】Python进度条tqdm的使用的更多相关文章
- tqdm:Python 进度条
Tqdm 是 Python 进度条库,可以在 Python 长循环中添加一个进度提示信息.用户只需要封装任意的迭代器,是一个快速.扩展性强的进度条工具库. 用法:tqdm(iterator) 代码地址 ...
- Python进度条模块tqdm实现任务进度可视化
一.前言 tqdm 是一个易用性强.扩展性高的 Python 进度条库,可以在 Python 长循环中添加一个进度提示信息,我们只需要封装任意的迭代器 tqdm(iterator) 即可. 二.安装 ...
- 2019年的代码都写完了吗?不如做个Python进度条看看还剩多少
我们都知道,进度条是用来直观展示流程所需时间的优秀工具,以免我们担心流程会突然挂掉,而且我们可以用它来预测代码运行是否正常,借助进度条,每个人都能直观地看到脚本最新的进展情况. 如果你之前没用过进度条 ...
- Python - 进度条库 tqdm
前言 在写生成器的时候,网上看到一个进度条库,感觉蛮有意思,记录下 这个库感觉只有在调试的时候会用到,不做深入学习 内置库,不需要安装 示例代码 from tqdm import tqdm for i ...
- 让你的程序炫起来!少有人知道但超酷的 Python 进度条开源库
本文适合有 Python 基础的朋友 本文作者:HelloGitHub-Anthony HelloGitHub 推出的<讲解开源项目>系列,本期介绍让你快速拥有完美进度条的 Python ...
- python 进度条的编写
背景: 在执行一些Python脚本时,经常出现执行脚本的过程当中,不知道脚本执行了百分之多少,这个问题一直都让我很苦恼.所以特意总结一下,进度条的编写. #!/usr/bin/env python2. ...
- Python · 进度条
(这里是本章会用到的 GitHub 地址) 我实现的这个进度条可能是可以当做一个第三方库来使用的(这个人好自大,啧),它支持记录并发程序的进度且损耗基本只来源于 Python 本身 先来看看我们的进度 ...
- Python 进度条显示
运行工具:Pycharm, import timescale = 50print("开始执行".center(scale//2,"-")) start = ti ...
- Python 进度条原理
#进度条原理 import sys,time for i in range(50): sys.stdout.write("#")#标准输出 #若不能够按照时间一个一个依次显示,则代 ...
随机推荐
- 如何使用Istio 1.6管理多集群中的微服务?
假如你正在一家典型的企业里工作,需要与多个团队一起工作,并为客户提供一个独立的软件,组成一个应用程序.你的团队遵循微服务架构,并拥有由多个Kubernetes集群组成的广泛基础设施. 由于微服务分布在 ...
- Java 添加、删除、替换、格式化Word中的文本(基于Spire.Cloud.SDK for Java)
Spire.Cloud.SDK for Java提供了TextRangesApi接口可通过addTextRange()添加文本.deleteTextRange()删除文本.updateTextRang ...
- spring 循环依赖的一次 理解
前言: 在看spring 循环依赖的问题中,知道原理,网上一堆的资料有讲原理. 但今天在看代码过程中,又产生了疑问. 疑问点如下: // 疑问点: 先进行 dependon 判断String[] de ...
- Excel绘制经典图表
1.柱形图 2.条形图 3.饼图---复合饼图 4.圆环图 5.组合图 设置不同的纵轴 6.漏斗图 其中:合计呈逐渐下降的趋势,可以用漏斗图进行展示! 绘制漏斗图首先需要构建辅助列,在插入图形的时候选 ...
- Python os.fstatvfs() 方法
概述 os.fstatvfs() 方法用于返回包含文件描述符fd的文件的文件系统的信息,类似 statvfs().高佣联盟 www.cgewang.com Unix上可用. fstatvfs 方法返回 ...
- Python3.x+Fiddler抓取APP数据
随着移动互联网的市场份额逐步扩大,手机APP已经占据我们的生活,以往的数据分析都借助于爬虫爬取网页数据进行分析,但是新兴的产品有的只有APP,并没有网页端这对于想要提取数据的我们就遇到了些问题,本章以 ...
- 深入探究JVM之方法调用及Lambda表达式实现原理
@ 目录 前言 正文 解析 分派 静态分派 动态分派 单分派和多分派 动态分派的实现 Lambda表达式的实现原理 MethodHandle 总结 前言 在最开始讲解JVM内存结构的时候有简单分析过方 ...
- Linux探测工具BCC(可观测性)
BCC(可观测性) 目录 BCC(可观测性) 简介 动机 版本要求 安装 安装依赖 安装和编译LLVM 安装和编译BCC windows源码查看 BCC的基本使用 工具讲解 execsnoop ope ...
- Java编译解释之cmd
一.编译 1. javac 类名.java (在类当前目录下) 2. javac 类的全路径 二.解释 1. java 类名(在类当前目录下) 2. java -cp 类的当前目录路径 类名
- Setup Factory 9 打包安装程序过程中提示安装.net4.5、并启用md5加密算法
1.在Before Installing选项卡中选择Ready to Install,点击Edit进入编辑窗口,切到最后一个选项卡Actions,把判断内容复制进去 -- These actions ...