简体   繁体   English

将 tqdm 进度条与 asyncio 一起使用

[英]Use tqdm progress bar with asyncio

I am trying to create a single progress bar that will be updated whenever an async task is done.我正在尝试创建一个进度条,只要异步任务完成,该进度条就会更新。

I have the following code我有以下代码

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)

The above code generates a single progress bar as but it is not updated until all tasks are finished (it shows either 0% or 100% while there's more than a single task)上面的代码生成一个进度条,但直到所有任务完成后才会更新(当有多个任务时,它显示 0% 或 100%)

I also tried using tqdm.asyncio.tqdm.gather我也尝试使用tqdm.asyncio.tqdm.gather

with tqdm(total=len(input_paths)):
     scan_results = await tqdm.gather(*[self.run_scan(i) for i in input_paths])

The above code generates multiple progress bars and as in the previous code block, it shows either 0% or 100%上面的代码生成多个进度条,和前面的代码块一样,它显示 0% 或 100%

My starting point was我的出发点是

scan_results = await asyncio.gather(*[self.run_scan(i)for i in input_paths])

Would appreciate your help on making it work with a single and dynamic progress bar感谢您的帮助,使其与单个动态进度条一起工作

If you call self.pbar.update(1) inside the run_scan scan method after creating concurrent tasks, each task will update the pbar for self.如果在创建并发任务后在run_scan扫描方法中调用self.pbar.update(1) ,每个任务都会为自己更新pbar So your class should look like the following所以你的班级应该如下所示

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