【发布时间】:2019-12-21 12:26:12
【问题描述】:
我试图弄清楚是否有可能将自定义异常抛出到正在运行的 asyncio 任务中,类似于 Task.cancel(self) 所实现的,它计划在底层协程中引发 CancelledError。
我遇到了Task.get_coro().throw(exc),但调用它似乎就像打开一大罐蠕虫一样,因为我们可能会让任务处于糟糕的状态。特别是考虑到task is throwing CancelledError into its coroutine 时发生的所有机制。
考虑以下示例:
import asyncio
class Reset(Exception):
pass
async def infinite():
while True:
try:
print('work')
await asyncio.sleep(1)
print('more work')
except Reset:
print('reset')
continue
except asyncio.CancelledError:
print('cancel')
break
async def main():
infinite_task = asyncio.create_task(infinite())
await asyncio.sleep(0) # Allow infinite_task to enter its work loop.
infinite_task.get_coro().throw(Reset())
await infinite_task
asyncio.run(main())
## OUTPUT ##
# "work"
# "reset"
# "work"
# hangs forever ... bad :(
我尝试做的事情是否可行?感觉好像我不应该像这样操纵底层协程。有什么解决方法吗?
【问题讨论】:
标签: python python-3.x python-asyncio