【问题标题】:How to get return from event loop functions如何从事件循环函数中获取返回
【发布时间】:2020-07-14 17:14:37
【问题描述】:

我是异步的新手。 所以,我的目标是从事件循环中获得一系列响应。毕竟我真的不明白这个return html_text 去了哪里。 能否请您更正我的代码或提供替代解决方案?

urls = [https://www.google.com, https://www.youtube.com/]

async def r_get(url):
    async with aiohttp.ClientSession() as session:
        async with session.get(url, headers=headers) as resp:
            resp.encoding = 'utf-8'
            html_text = await resp.text())
    return html_text


urls = [asyncio.ensure_future(r_get(url)) for url in urls_with_id]

loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.gather(*urls))

【问题讨论】:

    标签: asynchronous async-await python-asyncio


    【解决方案1】:

    run_until_complete 返回它运行的协程返回的值。反过来,gather 返回它等待完成的协程返回值的元组。当两者一起使用时,run_until_complete(gather(a(), b(), c())) 将返回一个由a()b()c() 分别返回的值组成的元组。

    在您的情况下,只需将结果分配给变量即可:

    results = loop.run_until_complete(asyncio.gather(*urls))
    # ...use results...
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-08-29
      • 1970-01-01
      • 2021-10-20
      • 2015-08-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多