捕获 Python 2.6 之前的警告

发布于 2024-08-18 11:17:24 字数 231 浏览 4 评论 0原文

在 Python 2.6 中,可以通过使用

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

2.6 之前的 Python 版本来抑制警告模块中的警告,但不支持 with ,所以我想知道是否有上述方法的替代方案可以与 pre 一起使用-2.6版本?

In Python 2.6 it is possible to suppress warnings from the warnings module by using

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

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

木格 2024-08-25 11:17:24

这类似于:

# 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,了解有关如何使用语句可以代替try/finally。

This is similar:

# 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

Edit: Without the try/finally, the original warning filters would not be restored if fxn() threw an exception. See PEP 343 for more discussion on how the with statement serves to replace try/finally when used like this.

土豪 2024-08-25 11:17:24

根据您需要支持的最低版本,使用 Python 2.5

from __future__ import with_statement

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

Depending on what the minimum version you need to support using Python 2.5's

from __future__ import with_statement

might be an option, else you'll probably need to fallback to what Jon suggested.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文