gpt4 book ai didi

python - 为 asyncio 制作 tqdm 进度条

转载 作者:行者123 更新时间:2023-12-03 15:48:32 40 4
gpt4 key购买 nike

我正在尝试使用收集的异步任务的 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/

40 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com