Python asyncio:loop.run“直到完成(loop.create)”任务(f))打印”;“从未检索到任务异常”;尽管它显然是被传播的

Python asyncio:loop.run“直到完成(loop.create)”任务(f))打印”;“从未检索到任务异常”;尽管它显然是被传播的,python,python-3.x,exception,coroutine,python-asyncio,Python,Python 3.x,Exception,Coroutine,Python Asyncio,出于某些原因,此程序打印以下警告: Task exception was never retrieved future: <Task finished coro=<coro() done, defined at /usr/lib64/python3.4/asyncio/coroutines.py:139> exception=SystemExit(2,)> SystemExit似乎是一个特例。例如,如果引发并捕获一个异常,则不会看到任何错误。 解决方法似乎是使用Task

出于某些原因,此程序打印以下警告:

Task exception was never retrieved
future: <Task finished coro=<coro() done, defined at /usr/lib64/python3.4/asyncio/coroutines.py:139> exception=SystemExit(2,)>

SystemExit
似乎是一个特例。例如,如果引发并捕获一个
异常
,则不会看到任何错误。 解决方法似乎是使用
Task.exception()
手动检索异常:

编辑


实际上,所有的
BaseException
子类都会这样做。

我认为这是因为
SystemExit
KeyboardInterrupt
是不同的情况。例如,正常
异常
不会导致相同的问题

您可以将
comain
coroutine链接到另一个内,以如下方式使用异常:

#!/usr/bin/env python3

import asyncio

@asyncio.coroutine
def comain():
    raise SystemExit(2)

@asyncio.coroutine
def another():
    try:
        yield from comain()
    except SystemExit:
        print ("consumed")

def main():
    loop = asyncio.get_event_loop()
    task = loop.create_task(another())
    try:
        loop.run_until_complete(task)
    except SystemExit:
        print("caught SystemExit!")
        raise
    finally:
        loop.close()

if __name__ == "__main__":
    main()

这里-我正在调用
other()
而不是
comain()
,在
other()
内部,我正在处理
comain()
中的异常

是否有任何理由不使用
循环。运行_直到完成(comain())
并按预期工作?我需要一个任务对象,因为我在
键盘中断
处理程序中调用了
任务。取消()
(此代码段中未显示)。您可以将
如果不是任务。取消():任务。结果()
添加到finally块中。虽然我不知道您是否需要手动调用
task.result()
task.exception()
(我希望
运行直到\u complete()
为您执行),但我的意图是让此异常转移到顶层,因此解释器将被终止。
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()
#!/usr/bin/env python3

import asyncio

@asyncio.coroutine
def comain():
    raise SystemExit(2)

@asyncio.coroutine
def another():
    try:
        yield from comain()
    except SystemExit:
        print ("consumed")

def main():
    loop = asyncio.get_event_loop()
    task = loop.create_task(another())
    try:
        loop.run_until_complete(task)
    except SystemExit:
        print("caught SystemExit!")
        raise
    finally:
        loop.close()

if __name__ == "__main__":
    main()