小编Eva*_*mas的帖子

asyncio 在任务中捕获 TimeoutError

我有asyncio.Task一段时间需要取消。在取消之前,任务需要做一些清理工作。根据文档,我应该只能在协程中调用 task.cancel 或asyncio.wait_for(coroutine, delay)拦截 an asyncio.TimeoutError,但以下示例不起作用。我尝试过拦截其他错误并调用task.cancel,但都没有成功。我是否误解了取消任务的工作原理?

@asyncio.coroutine
def toTimeout():
  try:
    i = 0
    while True:
      print("iteration ", i, "......"); i += 1
      yield from asyncio.sleep(1)
  except asyncio.TimeoutError:
    print("timed out")

def main():
  #... do some stuff
  yield from asyncio.wait_for(toTimeout(), 10)
  #... do some more stuff

asyncio.get_event_loop().run_until_complete(main())
asyncio.get_event_loop().run_forever()
Run Code Online (Sandbox Code Playgroud)

python python-3.x python-asyncio

3
推荐指数
1
解决办法
2万
查看次数

标签 统计

python ×1

python-3.x ×1

python-asyncio ×1