在Python中,如何将警告当作异常捕获?

230 投票
8 回答
168631 浏览
提问于 2025-04-16 15:37

我在Python代码中使用了一个第三方库(这个库是用C语言写的),但是它发出了警告。我想用try except这种写法来正确处理这些警告。请问有没有办法做到这一点?

8 个回答

45

如果你只是想让你的脚本在出现警告时就失败,可以在运行 python 时加上 -W 参数

python -W error foobar.py
78

引用一下Python手册中的内容(27.6.4. 测试警告):

import warnings

def fxn():
    warnings.warn("deprecated", DeprecationWarning)

with warnings.catch_warnings(record=True) as w:
    # Cause all warnings to always be triggered.
    warnings.simplefilter("always")
    # Trigger a warning.
    fxn()
    # Verify some things
    assert len(w) == 1
    assert issubclass(w[-1].category, DeprecationWarning)
    assert "deprecated" in str(w[-1].message)
279

要把警告当作错误来处理,只需要使用下面的代码:

import warnings
warnings.filterwarnings("error")

这样做之后,你就可以像处理错误一样处理警告了,比如下面的代码就可以正常工作:

try:
    some_heavy_calculations()
except RuntimeWarning:
    breakpoint()

你也可以通过运行下面的代码来重置警告的处理方式:

warnings.resetwarnings()

顺便说一下,我加这个回答是因为评论区里最好的回答拼写错了:写成了 filterwarnigns,其实应该是 filterwarnings

撰写回答