How to combine Tqdm with Asyncio in Python?

To combine Tqdm with Asyncio, you can use the tqdm.asyncio.tqdm function from Tqdm to wrap asynchronous operations.

Here is a sample code demonstrating how to use Tqdm to display a progress bar in asynchronous tasks.

import asyncio
from tqdm import tqdm
from tqdm.asyncio import tqdm as async_tqdm

async def async_task():
    # 模拟一个耗时的异步操作
    await asyncio.sleep(1)

async def main():
    tasks = [async_task() for _ in range(10)]  # 创建多个异步任务
    
    # 使用async_tqdm包装异步任务,并设置总数
    with async_tqdm(total=len(tasks)) as pbar:
        # 使用asyncio.gather来并发运行任务
        await asyncio.gather(*tasks, return_exceptions=True, loop=pbar.get_event_loop())

# 运行主函数
asyncio.run(main())

In the above code, an async_task function is first defined, which simulates a time-consuming async operation. Multiple async tasks are then created in the main function and wrapped with async_tqdm, setting the total number of progress bars to the number of tasks. Finally, asyncio.gather is used to concurrently run these tasks, while setting the progress bar’s event loop to the current task’s event loop.

Before running the above code, make sure to install the tqdm library by using the following command.

pip install tqdm
bannerAds