介绍
有时候在使用Python处理比较耗时操作的时候,为了便于观察处理进度,需要通过进度条将处理情况进行可视化展示,以便我们能够及时了解情况。
Tqdm 是一个快速,可扩展的Python进度条,可以实时输出处理进度而且占用的CPU资源非常少
,支持windows
、Linux
、mac
等系统,支持循环处理
、多进程
、递归处理
、还可以结合linux
的命令来查看处理进度。
使用pip就可以安装。
pip install tqdm
使用
可以迭代的对象
from tqdm import tqdm import time for i in tqdm(range(100)): time.sleep(0.1)
在使用tqdm的时候,可以将tqdm(range(100))替换为trange(100)。
from tqdm import tqdm,trange import time for i in trange(100): time.sleep(0.1)
观察处理的数据
通过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()
自定义进度条显示信息
通过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)
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]
转载自修炼之路。
对大多数人而言,
人生不是一场冒险,
而是一股无法抗拒的洪流。
《能不能请你安静点?》
——雷蒙德·卡佛
评论
742667 895887I genuinely dont accept this particular post. Nonetheless, I had searched with Google and Ive identified out that youre proper and I had been thinking within the improper way. Maintain on creating top quality material comparable to this. 879348
157291 678439For anybody who is interested in enviromentally friendly items, may possibly surprise for you the crooks to keep in mind that and earn under a holder basically because kind dissolved acquire various liters to crucial oil to make. daily deal livingsocial discount baltimore washington 702030
737902 439258All you need to have to know about News info to you. 900386
477551 524242When I originally commented I clicked the -Notify me when new feedback are added- checkbox and now every time a remark is added I get four emails with exactly the same comment. Is there any approach youll be able to remove me from that service? Thanks! 390421
477544 707994I believe that a simple and unassuming manner of life is greatest for every person, very best both for the body and the mind. 551082
881833 581634Really man or woman speeches want to seat giving observe into couples. Brand new sound system just before unnecessary men and women should always be mindful of generally senior general rule from public speaking, which is to be the mini. finest man speaches 117352
762147 941672I truly prize your piece of work, Fantastic post. 289022
350090 848762Id want to consult you here. Which isnt some thing Which i do! I enjoy reading a post that can make individuals feel. Also, appreciate your allowing me to comment! 133311
225628 834849Thanks for this amazing post! It has long been really helpful. I wish that you will carry on posting your wisdom with us. 568492
207877 89844Yeah bookmaking this wasnt a bad conclusion fantastic post! . 886436
658345 81278Couldn?t be produced any much better. Reading this post reminds me of my old room mate! He always kept talking about this. I will forward this report to him. Pretty certain he will possess a very good read. Thanks for sharing! 772444