在Python 2.6中,可以使用
来禁止来自警告模块的警告with warnings.catch_warnings():
warnings.simplefilter("ignore")
fxn()
2.6之前的Python版本不支持with
,所以我想知道上面的替代方案是否适用于2.6之前的版本?
答案 0 :(得分: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()引发异常,则不会恢复原始警告过滤器。有关with
语句在使用时如何替换try/finally
的更多讨论,请参阅PEP 343。
答案 1 :(得分:-1)
取决于使用Python 2.5支持的最低版本
from __future__ import with_statement
可能是一个选项,否则你可能需要回退到Jon的建议。