繁体   English   中英

将 tqdm 进度条与 asyncio 一起使用

[英]Use tqdm progress bar with asyncio

我正在尝试创建一个进度条,只要异步任务完成,该进度条就会更新。

我有以下代码

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()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM