在处理大批量文件时,单个服务器的文件数量可能到了2000+,需要对这些文件进行读取、计算、结果存储。
使用 print 可以打印详细信息,但当项目稳定后,不再需要debug信息,而需要简洁地看到进度,并将日志保存下来即可。
使用 tqdm 也可以对多进程任务的进度进行显示,代码示例如下:
"""
* Author:
* Date: 2022年4月19日
"""
import time
import concurrent.futures
from tqdm import tqdm
def cal_func(x, y):
"""
要调用的函数
@param x:
@param y:
@return:
"""
time.sleep(0.001) # to visualize the progress
hh = x * y * 2
return hh
def call_func_job(args):
"""
参数解包
@param args:
@return:
"""
return cal_func(*args)
def run(f, this_iter):
"""
主函数,运行多进程程序并显示进度条。
@param f:
@param this_iter:
@return:
"""
with concurrent.futures.ThreadPoolExecutor() as executor:
results = list(tqdm(executor.map(f, this_iter), total=len(this_iter)))
return results
if __name__ == '__main__':
zip_args = list(zip(range(10000),
range(10000)))
print(len(zip_args))
my_iter = zip_args
res = run(call_func_job, my_iter)
print(res)
得到的效果如图: