【问题标题】:Set result of 2 or more Async HTTP calls into named variables将 2 个或更多异步 HTTP 调用的结果设置为命名变量
【发布时间】:2017-01-05 12:46:20
【问题描述】:

我想要实现的是: tasks = [call(url) for url in urls]

call 是 Python3.5 中的 async 方法/coroutine 来执行 GET 请求,比如说aiohttp

所以基本上所有的 call 调用都是异步的。现在我可以运行asyncio.wait(tasks),然后在futures中一一访问结果。

但是,我想要的是,假设只有 2 个 url,然后: a, b = call(url1), call(url2)

就像你在 Koa 中通过产生一个数组来做的那样。如果可以的话,有什么帮助吗??

【问题讨论】:

  • 您希望呼叫同时发生还是顺序发生?
  • @dim 同时
  • 那么你需要使用asyncio.waitasyncio.gather 之类的东西。
  • 是的,我知道,但是怎么做呢?如何将其分配给命名变量而不是未来数组?
  • var1, var2 = loop.run_until_complete(asyncio.gather(task1, task2))

标签: python python-3.x asynchronous concurrency python-asyncio


【解决方案1】:

var1, var2 = loop.run_until_complete(asyncio.gather(task1, task2))

根据文档,gather 保留了它传递的序列的顺序

【讨论】:

    猜你喜欢
    • 2019-07-09
    • 2013-04-24
    • 2015-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多