出于某种原因,该程序打印出以下警告:
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()
最佳答案
SystemExit
似乎是一个特例。例如,如果您引发并捕获 Exception
,您将看不到任何错误。
解决这个问题的方法似乎是使用 Task.exception()
手动检索异常:
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!")
task.exception()
raise
finally:
loop.close()
if __name__ == "__main__":
main()
编辑
实际上,所有 BaseException
子类都会以这种方式运行。
关于python - asyncio : loop. run_until_complete(loop.create_task(f)) 打印 "Task exception was never retrieved",即使它显然已传播,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34441790/