【问题标题】:asyncio aiohttp progress bar with tqdm带 tqdm 的 asyncio aiohttp 进度条
【发布时间】:2016-06-18 20:21:04
【问题描述】:

我正在尝试集成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)

【问题讨论】:

    标签: progress-bar python-3.5 python-asyncio aiohttp tqdm


    【解决方案1】:

    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 函数中使用。

    【讨论】:

    • @j-f-sebastien 可爱!谢谢你告诉我
    猜你喜欢
    • 2020-07-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-13
    相关资源
    最近更新 更多