7

在 Python 2.6 中,可以通过使用来抑制警告模块中的警告

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

但是, 2.6 之前的 Python 版本不支持with,所以我想知道是否有上述替代方案可以与 2.6 之前的版本一起使用?

4

2 回答 2

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在这样使用时如何替换的讨论。

于 2010-01-13T19:53:15.797 回答
-1

取决于您需要使用 Python 2.5 支持的最低版本

from __future__ import with_statement

可能是一种选择,否则您可能需要回退到 Jon 建议的内容。

于 2010-01-13T19:56:38.347 回答