简述:tqdm就能非常完美的支持和解决通过进度条将处理情况进行可视化展示的问题,可以实时输出处理进度而且占用的CPU资源非常少,支持windows、Linux、mac等系统,支持循环处理、多进程、递归处理、还可以结合linux的命令来查看处理情况,等进度展示。
安装
pip install tqdm
使用
迭代对象处理
from tqdm import tqdm
import time
for i in tqdm(range(100)):
time.sleep(0.1)
pass
可将tqdm(range(100)) 替换为trange(100)
from tqdm import tqdm,trange
import time
for i in trange(100):
time.sleep(0.1)
pass
手动设置进度
form tqdm import tqdm
import time
#total参数设置进度条的总长度
with tqdm(total=100) as pbar:
for i in range(100):
time.sleep(0.05)
#每次更新进度条的长度
pbar.update(1)
updata中的para 与range中的para的乘积要等于total,不然会使进度条未到100%或已到100%,总量依旧在更新,可适当做变速处理。
自定义进度条显示信息
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)
#设置进度条右边显示的信息(按照assic码排序)
t.set_postfix(loss=random(),gen=randint(1,999),str="h",lst=[1,2])
time.sleep(0.1)
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.1)
t.postfix[1]["value"] = i / 2
t.update()
Batch 4.5
多层循环进度条
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中由于不支持某些字符,会出现进度条位置错乱。
在命令行执行如下:
多进程进度条
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://mp.weixin.qq.com/s?__biz=MzU3MDgwOTIyOQ%3D%3D&mid=2247483796&idx=1&sn=acab4353b7d57199bb5e06c5b44f2045&scene=45#wechat_redirect