python - 为 asyncio 制作 tqdm 进度条

标签 python tqdm

我正在尝试使用收集的异步任务的 tqdm 进度条。

希望在完成任务后逐步更新进度条。试过代码:

import asyncio
import tqdm
import random

async def factorial(name, number):
    f = 1
    for i in range(2, number+1):
        await asyncio.sleep(random.random())
        f *= i
    print(f"Task {name}: factorial {number} = {f}")

async def tq(flen):
    for _ in tqdm.tqdm(range(flen)):
        await asyncio.sleep(0.1)

async def main():
    # Schedule the three concurrently

    flist = [factorial("A", 2),
        factorial("B", 3),
        factorial("C", 4)]

    await asyncio.gather(*flist, tq(len(flist)))

asyncio.run(main())

...但这只是完成了 tqdm 条,然后处理阶乘。

有没有办法在每个 asyncio 任务完成后让进度条移动?

最佳答案

现在,我不是特别熟悉 asyncho ,虽然我用过 tqdm在 python 中的多进程方面取得了一些成功。
对您的代码进行的以下更改似乎会更新进度条并同时打印结果,这可能足以让您入门。

responses = [await f
                 for f in tqdm.tqdm(asyncio.as_completed(flist), total=len(flist))]

以上应该替换await asyncio.gather(*flist, tq(len(flist)))在您的 main定义。

有关更多信息,以上内容的灵感来自 asyncio aiohttp progress bar with tqdm

为了只打印一次栏并更新它,我已经完成了以下操作,更新了进度栏的描述以包含您的消息:

import asyncio
import tqdm


async def factorial(name, number):
    f = 1
    for i in range(2, number + 1):
        await asyncio.sleep(1)
        f *= i
    return f"Task {name}: factorial {number} = {f}"

async def tq(flen):
    for _ in tqdm.tqdm(range(flen)):
        await asyncio.sleep(0.1)


async def main():
    # Schedule the three concurrently

    flist = [factorial("A", 2),
             factorial("B", 3),
             factorial("C", 4)]

    pbar = tqdm.tqdm(total=len(flist))
    for f in asyncio.as_completed(flist):
        value = await f
        pbar.set_description(value)
        pbar.update()

if __name__ == '__main__':
    asyncio.run(main())

关于python - 为 asyncio 制作 tqdm 进度条,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61041214/

相关文章:

python - 如何按列获取重复数字的长度?

python-matplotlib AttributeError Axes3D 对象没有属性 set_zticks

python glob 应用通配符仅在某些目录中搜索

python - Mock_open CSV 文件未获取任何数据

python-3.x - 如何让TQDM进度条在KB和MB之间自动更新

Python 的 ftplib 与 tqdm

python - 如何从 subprocess.Popen.stdout 读取所有可用数据(非阻塞)?

python - 我可以向 tqdm 进度条添加消息吗?

python - tqdm:更新总数不重置时间已过