问题
使用 Python 的 asyncio
模块,如何从多个协程中选择第一个结果?
例子
我可能想在等待队列时实现超时:
result = yield from select(asyncio.sleep(1),
queue.get())
类似操作
这类似于 Go's select
或 Clojure's core.async.alt!
.这有点像 asyncio.gather
的逆过程(收集就像all
,选择就像any
。)
最佳答案
简单的解决方案,通过使用 asyncio.wait
及其 FIRST_COMPLETED
参数:
import asyncio
async def something_to_wait():
await asyncio.sleep(1)
return "something_to_wait"
async def something_else_to_wait():
await asyncio.sleep(2)
return "something_else_to_wait"
async def wait_first():
done, pending = await asyncio.wait(
[something_to_wait(), something_else_to_wait()],
return_when=asyncio.FIRST_COMPLETED)
print("done", done)
print("pending", pending)
asyncio.get_event_loop().run_until_complete(wait_first())
给出:
done {<Task finished coro=<something_to_wait() done, defined at stack.py:3> result='something_to_wait'>}
pending {<Task pending coro=<something_else_to_wait() running at stack.py:8> wait_for=<Future pending cb=[Task._wakeup()]>>}
Task was destroyed but it is pending!
task: <Task pending coro=<something_else_to_wait() running at stack.py:8> wait_for=<Future pending cb=[Task._wakeup()]>>
关于python - 从异步中的两个协程中选择第一个结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31900244/