- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
给定以下程序:
import asyncio
async def coro():
future = asyncio.Future()
future.cancel()
print(future) # <Future cancelled>
await future # no output
loop = asyncio.get_event_loop()
loop.create_task(coro())
loop.run_forever()
为什么await future
抛出的CancelledError
没有显示?将 await future
显式包装在 try/except
中表明它发生了。其他未处理的错误显示为 Task exception was never returned
,如下所示:
async def coro2():
raise Exception('foo')
loop.create_task(coro2())
为什么等待取消的 future 不是这种情况?
附加问题:如果协程等待取消的 Future,内部会发生什么?它会永远等待吗?我必须做任何“清理”工作吗?
最佳答案
Why is the
CancelledError
thrown byawait future
not shown?
未显示异常,因为您从未实际检索 coro
的结果。如果您以任何方式检索它,例如通过调用任务的 result()
方法或只是等待它,您将在检索它的位置得到预期的错误。观察回溯结果的最简单方法是将 run_forever()
更改为 run_until_complete(coro())
。
What happens internally if a coroutine awaits a cancelled Future? Does it wait forever? Do I have to do any "cleanup" work?
它不会永远等待,它会在await
处收到CancelledError
。您已经通过在 await future
周围添加 try/except 发现了这一点。您需要执行的清理与任何其他异常相同 - 要么什么都不做,要么使用 with
和 finally
来确保您获取的资源在退出的情况。
Other unhandled errors are shown with
Task exception was never retrieved
[...] Why is this not the case for awaiting cancelled Futures?
因为Future.cancel
intentionally disables回溯的记录。这是为了避免在取消 future 时输出“从未检索到异常”。由于 CancelledError
通常是从外部注入(inject)的,并且可能在(几乎)任何时刻发生,因此检索它几乎没有任何值(value)。
如果在一个异常情况下显示回溯听起来很奇怪,但在另一个异常情况下则不显示回溯,请注意,失败任务的回溯一开始就会尽力显示。使用 create_task
创建的任务并且不等待有效地“在后台”运行,就像没有join()
ed的线程一样。但与线程不同的是,协程具有“结果”的概念,可以是从协程返回的对象,也可以是由它引发的异常。协程的返回值由result提供。它的任务。当协程因异常退出时,结果会封装异常,并在检索结果时自动引发。这就是为什么 Python 无法像线程由于未处理的异常而终止时那样立即打印回溯 - 它必须等待某人实际检索结果。只有当结果包含异常的 Future
即将被垃圾收集时,Python 才能知道结果永远不会被检索到。然后,它显示警告和回溯,以避免异常静默传递。
关于python - 异步: Why is awaiting a cancelled Future not showing CancelledError?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51346002/
我是一名优秀的程序员,十分优秀!