捕获Python 2.6之前的警告

7 投票
2 回答
883 浏览
提问于 2025-04-15 17:59

在Python 2.6中,可以通过使用下面的代码来抑制来自警告模块的警告信息:

with warnings.catch_warnings():
    warnings.simplefilter("ignore")
    fxn()

不过在2.6之前的Python版本中,不支持with这个写法。所以我在想,有没有其他方法可以在2.6之前的版本中实现同样的效果呢?

2 个回答

-1

根据你需要支持的最低版本,如果是 Python 2.5 的话,

from __future__ import with_statement

这可能是一个选择,否则你可能需要回到 Jon 提出的建议。

3

这很相似:

# Save the existing list of warning filters before we modify it using simplefilter().
# Note: the '[:]' causes a copy of the list to be created. Without it, original_filter
# would alias the one and only 'real' list and then we'd have nothing to restore.
original_filters = warnings.filters[:]

# Ignore warnings.
warnings.simplefilter("ignore")

try:
    # Execute the code that presumably causes the warnings.
    fxn()

finally:
    # Restore the list of warning filters.
    warnings.filters = original_filters

补充:如果没有 try/finally,那么如果 fxn() 抛出一个异常,原来的警告过滤器就不会被恢复。想了解更多,可以查看 PEP 343,里面详细讨论了 with 语句如何在这种情况下替代 try/finally

撰写回答