【发布时间】:2016-03-30 05:58:57
【问题描述】:
由于某种原因,该程序会打印以下警告:
Task exception was never retrieved
future: <Task finished coro=<coro() done, defined at /usr/lib64/python3.4/asyncio/coroutines.py:139> exception=SystemExit(2,)>
即使异常被清楚地检索和传播,因为caught SystemExit!被打印到终端,并且进程状态代码变为2。
Python 2 和 trollius 也会发生同样的事情。
我错过了什么吗?
#!/usr/bin/env python3
import asyncio
@asyncio.coroutine
def comain():
raise SystemExit(2)
def main():
loop = asyncio.get_event_loop()
task = loop.create_task(comain())
try:
loop.run_until_complete(task)
except SystemExit:
print("caught SystemExit!")
raise
finally:
loop.close()
if __name__ == "__main__":
main()
【问题讨论】:
-
有什么理由不使用
loop.run_until_complete(comain()),它可以按预期工作吗? -
我需要一个任务对象,因为我在
KeyboardInterrupt处理程序中调用了task.cancel()(未在此 sn-p 中显示)。 -
您可以将
if not task.cancelled(): task.result()添加到 finally 块中。虽然我不知道你必须手动调用task.result()或task.exception()是否是预期的行为(我希望run_until_complete()为你做这件事)。
标签: python python-3.x exception coroutine python-asyncio