gpt4 book ai didi

progress-bar - 使用tqdm的asyncio aiohttp进度栏

转载 作者:行者123 更新时间:2023-12-03 23:22:50 31 4
gpt4 key购买 nike

我正在尝试集成tqdm进度栏以监视在Python 3.5中使用aiohttp生成的POST请求。我有一个工作进度栏,但似乎无法使用as_completed()收集结果。指针感激不尽。

我发现的示例建议使用以下模式,该模式与Python 3.5 async def定义不兼容:

for f in tqdm.tqdm(asyncio.as_completed(tasks), total=len(coros)):
yield from f

没有进度条的有效(尽管已编辑)异步代码:
def async_classify(records):

async def fetch(session, name, sequence):
url = 'https://app.example.com/api/v0/search'
payload = {'sequence': str(sequence)}
async with session.post(url, data=payload) as response:
return name, await response.json()

async def loop():
auth = aiohttp.BasicAuth(api_key)
conn = aiohttp.TCPConnector(limit=100)
with aiohttp.ClientSession(auth=auth, connector=conn) as session:
tasks = [fetch(session, record.id, record.seq) for record in records]
responses = await asyncio.gather(*tasks)
return OrderedDict(responses)

这是我修改 loop()的失败尝试:
async def loop():
auth = aiohttp.BasicAuth(api_key)
conn = aiohttp.TCPConnector(limit=100)
with aiohttp.ClientSession(auth=auth, connector=conn) as session:
tasks = [fetch(session, record.id, record.seq) for record in records]
for f in tqdm.tqdm(asyncio.as_completed(tasks), total=len(tasks)):
await f
responses = await asyncio.gather(f)
print(responses)

最佳答案

await f返回一个响应。您为什么还要将已经完成的Future传递给asyncio.gather(f),尚不清楚。

尝试:

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

Python 3.6实现 PEP 530 -- Asynchronous Comprehensions:
responses = [await f
for f in tqdm.tqdm(asyncio.as_completed(tasks), total=len(tasks))]

现在可以在 async def函数中使用。

关于progress-bar - 使用tqdm的asyncio aiohttp进度栏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37901292/

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