失败而不是打印 "Exception ignored in: <coroutine..."
Fail instead of printing "Exception ignored in: <coroutine..."
当明确告诉 Python 将 RuntimeWarning
视为异常时,Warning
成功变为 Exception
。但是现在我得到一个 Exception ignored
,程序仍然没有在它应该失败的地方失败。最小可重现示例:
import asyncio
import warnings
async def main():
asyncio.sleep(1)
print("I don't want this printed.")
warnings.filterwarnings("error", category=RuntimeWarning)
asyncio.run(main())
Exception ignored in: <coroutine object sleep at 0x7f1e4f3d1b40>
Traceback (most recent call last):
File "/home/teresaejunior/.asdf/installs/python/3.9.2/lib/python3.9/warnings.py", line 506, in _warn_unawaited_coroutine
warn(msg, category=RuntimeWarning, stacklevel=2, source=coro)
RuntimeWarning: coroutine 'sleep' was never awaited
I don't want this printed.
如何阻止 Python 忽略 warnings
模块引发的异常?
How can I stop Python from ignoring this exception?
遗憾的是,我不认为你可以,至少不能以明显的方式。问题是这个警告是在协程对象被销毁时打印的,这是 Python 可以确定你永远不会等待协程的最早时间点。
无法从析构函数中引发异常,因为析构函数在垃圾收集期间和其他敏感时间运行。所以当 Python 当时检测到异常时,它只是忽略它,正如消息所说。
当明确告诉 Python 将 RuntimeWarning
视为异常时,Warning
成功变为 Exception
。但是现在我得到一个 Exception ignored
,程序仍然没有在它应该失败的地方失败。最小可重现示例:
import asyncio
import warnings
async def main():
asyncio.sleep(1)
print("I don't want this printed.")
warnings.filterwarnings("error", category=RuntimeWarning)
asyncio.run(main())
Exception ignored in: <coroutine object sleep at 0x7f1e4f3d1b40>
Traceback (most recent call last):
File "/home/teresaejunior/.asdf/installs/python/3.9.2/lib/python3.9/warnings.py", line 506, in _warn_unawaited_coroutine
warn(msg, category=RuntimeWarning, stacklevel=2, source=coro)
RuntimeWarning: coroutine 'sleep' was never awaited
I don't want this printed.
如何阻止 Python 忽略 warnings
模块引发的异常?
How can I stop Python from ignoring this exception?
遗憾的是,我不认为你可以,至少不能以明显的方式。问题是这个警告是在协程对象被销毁时打印的,这是 Python 可以确定你永远不会等待协程的最早时间点。
无法从析构函数中引发异常,因为析构函数在垃圾收集期间和其他敏感时间运行。所以当 Python 当时检测到异常时,它只是忽略它,正如消息所说。