ast*_*rog 7 python warnings suppress-warnings
In Python 2.6 it is possible to suppress warnings from the warnings module by using
with warnings.catch_warnings():
warnings.simplefilter("ignore")
fxn()
Run Code Online (Sandbox Code Playgroud)
Versions of Python before 2.6 don't support with however, so I'm wondering if there alternatives to the above that would work with pre-2.6 versions?
这很相似:
# 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
Run Code Online (Sandbox Code Playgroud)
编辑:如果没有try/finally,如果 fxn() 抛出异常,则原始警告过滤器将不会被恢复。请参阅PEP 343,了解有关该语句在这样使用时如何with进行替换的更多讨论。try/finally