【问题标题】:How to use asyncio and await on a variable amount of futures?如何在可变数量的期货上使用 asyncio 和等待?
【发布时间】:2019-06-13 02:50:47
【问题描述】:

我正在尝试将 asyncio 与我拥有的需要一段时间才能运行的方法一起使用。我想用稍微不同的输入多次调用相同的方法,我不在乎哪个调用首先完成,我只想在它们全部完成后收集所有结果(asyncio 循环的主要候选者,对吗?)这里有一些当我知道要调用我的方法多少次时,我一直在使用的代码:

async def main():
    loop = asyncio.get_event_loop()
    future1 = loop.run_in_executor(None, myhttpreq, 'US')
    future2 = loop.run_in_executor(None, myhttpreq, 'RU')
    future3 = loop.run_in_executor(None, myhttpreq, 'CN')
    response1 = await future1
    response2 = await future2
    response3 = await future3
    print(response1)
    print(response2)
    print(response3)

您可以从 myhttpreq 传递的参数中看出,此方法需要这么长时间的原因是因为它调用了来自世界各地的 endpints。我的问题是这样的:

假设我要调用的国家/地区列表非常多变,我如何生成并等待可变数量的期货?

【问题讨论】:

    标签: python python-asyncio


    【解决方案1】:

    我最终这样做了:

    async def main2(countries):
    loop = asyncio.get_event_loop()
    futures = []
    for country in countries:
        futures.append(loop.run_in_executor(None, myhttpreq, country))
    
    for future in futures:
        print(await future)
    

    这看起来很愚蠢吗?

    【讨论】:

      猜你喜欢
      • 2014-06-17
      • 2020-10-31
      • 1970-01-01
      • 2021-07-26
      • 1970-01-01
      • 2016-03-24
      • 2013-06-29
      • 2015-08-24
      • 1970-01-01
      相关资源
      最近更新 更多