【问题标题】:Catching warnings pre-python 2.6在 python 2.6 之前捕获警告
【发布时间】:2010-01-13 19:42:24
【问题描述】:

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

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

但是,2.6 之前的 Python 版本不支持 with,所以我想知道是否有其他替代方法可以用于 2.6 之前的版本?

【问题讨论】:

    标签: python warnings suppress-warnings


    【解决方案1】:

    这是类似的:

    # 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

    【讨论】:

    • Morgoth:复制过滤器,修改它们,调用 fxn,最后将过滤器重置为原始值。与 2.6 上下文管理器所做的几乎完全相同。
    • 感谢您的解释 - 为什么最后需要尝试...?
    • 我添加了 cmets 来解释代码并说明为什么 try ... finally 更好。
    【解决方案2】:

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

    from __future__ import with_statement
    

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

    【讨论】:

    • 正如 Pär Wieslander 在我尝试这个答案时向我指出的那样(我现在看到我不应该删除它),catch_warnings() 是在 2.6 中引入的,所以在这种情况下,只需使用 with声明没有帮助(除非你想复制catch_warnings()的实现。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-05-02
    • 2011-01-07
    • 2016-04-24
    • 2015-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多