我正在尝试创建一个进度条,每当异步任务完成时都会更新该进度条。
我有以下代码
scan_results = []
tasks = [self.run_scan(i) for i in input_paths]
pbar = tqdm(total=len(tasks), desc='Scanning files')
for f in asyncio.as_completed(tasks):
value = await f
pbar.update(1)
scan_results.append(value)
上面的代码生成一个进度条,但直到所有任务完成后才会更新(当有多个任务时,它显示 0% 或 100%)
我还尝试使用tqdm.asyncio.tqdm.gather
with tqdm(total=len(input_paths)):
scan_results = await tqdm.gather(*[self.run_scan(i) for i in input_paths])
上面的代码生成多个进度条,与前面的代码块一样,它显示 0% 或 100%
我的出发点是
scan_results = await asyncio.gather(*[self.run_scan(i)for i in input_paths])
非常感谢您帮助使其与单个动态进度条一起使用
最佳答案
如果您在创建并发任务后在 run_scan
扫描方法中调用 self.pbar.update(1)
,则每个任务都会更新 pbar
> 为了自己。所以你的类应该如下所示
class Cls:
async def run_scan(self, path):
...
self.pbar.update(1)
def scan(self, input_paths):
loop = asyncio.get_event_loop()
tasks = [loop.create_task(self.run_scan(i)) for i in input_paths]
self.pbar = tqdm(total=len(input_paths), desc='Scanning files')
loop.run_until_complete(asyncio.gather(*tasks))
loop.close()
关于python - 将 tqdm 进度条与 asyncio 结合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72645095/