【发布时间】:2018-09-25 12:16:56
【问题描述】:
基本上我想要:
await action1()
await action2()
return result
两个操作都有一个超时,并且 - 这很重要 - 有一条错误消息告诉哪个操作超时。
为了比较,只需一个操作:
try:
await asyncio.wait_for(action(), timeout=1.0)
except asyncio.TimeoutError:
raise RuntimeError("Problem")
现在有两个动作我有这个但不喜欢它。
import asyncio
async def a2():
try:
await asyncio.sleep(1.0)
except asyncio.CancelledError:
raise RuntimeError("Problem 1") from None
try:
await asyncio.sleep(1.0)
except asyncio.CancelledError:
raise RuntimeError("Problem 2") from None
return True
async def test():
loop = asyncio.get_event_loop()
action_task = loop.create_task(a2())
# timeouts: 0.5 -> Problem1 exc; 1.5 -> Problem2 exc; 2.5 -> OK
try:
await asyncio.wait_for(action_task, timeout=0.5)
except asyncio.TimeoutError:
pass
result = await action_task
asyncio.get_event_loop().run_until_complete(test())
我觉得拥有以下内容真的违反直觉:
except asyncio.TimeoutError:
pass
超时处理是主要功能。你能推荐一个更好的方法吗?
【问题讨论】:
-
@bobah 这不是重复的,我想先运行动作 1,然后运行动作 2。
-
公平点,我撤回了接近投票
标签: python python-asyncio