我正在尝试创建一个进度条,当异步任务完成时,它将被更新。
我有以下代码
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])希望您能帮助它使用一个单一的动态进度条。
发布于 2022-06-16 12:52:47
如果在创建并发任务后在self.pbar.update(1)扫描方法中调用run_scan,则每个任务都将更新pbar for self。因此,您的类应该如下所示
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()https://stackoverflow.com/questions/72645095
复制相似问题