【问题标题】:How do I get warnings.warn to issue a warning and not ignore the line?如何让 warnings.warn 发出警告而不忽略该行?
【发布时间】:2014-01-24 10:56:09
【问题描述】:

我正在尝试提出一个DeprecationWarning,并根据文档中显示的示例使用代码 sn-p。 http://docs.python.org/2/library/warnings.html#warnings.warn

官方

def deprecation(message):
    warnings.warn(message, DeprecationWarning, stacklevel=2)

我的

import warnings
warnings.warn("This is a warnings.", DeprecationWarning, stacklevel=2) is None  # returns True

我尝试删除 stacklevel 参数,将其设置为负数、0、2 和 20000。警告总是被默默吞下。它不会发出警告或引发异常。它只是忽略该行并返回None。文档没有提到忽略的标准。发送消息,使 warnings.warn 正确发出 Userwarning.

什么可能导致这种情况,我如何得到警告以实际发出警告?

【问题讨论】:

    标签: python python-2.7 warnings suppress-warnings


    【解决方案1】:

    警告模块根据特定条件实现对警告的过滤。你可以通过打印warnings.filters来显示默认过滤器:

    $ python -c "import warnings; print(warnings.filters)"
    [('ignore', None, <type 'exceptions.DeprecationWarning'>, None, 0),
     ('ignore', None, <type 'exceptions.PendingDeprecationWarning'>, None, 0),
     ('ignore', None, <type 'exceptions.ImportWarning'>, None, 0),
     ('ignore', None, <type 'exceptions.BytesWarning'>, None, 0)]
    

    如您所见,DeprecationWarning 默认被忽略。您可以使用warnings 模块和-W command-line option to Python 中的函数来配置过滤器——详情请参阅文档。

    例子:

    $ python -Wall
    Python 2.7.3 (default, Sep 26 2013, 20:03:06) 
    [GCC 4.6.3] on linux2
    Type "help", "copyright", "credits" or "license" for more information.
    >>> import warnings
    >>> warnings.warn("test", DeprecationWarning)
    __main__:1: DeprecationWarning: test
    

    【讨论】:

    • 有没有办法以编程方式打开所有警告? (例如不在命令行?)
    • @MarcelWilson 类似warnings.simplefilter("always")(或warnings.simplefilter("default"),如果您只想查看每个警告的第一次出现)。详情请阅读warnings 模块文档。
    【解决方案2】:

    来自文档:

    默认情况下,Python 安装了几个警告过滤器,可以是 被传递给 -W 的命令行选项覆盖并调用 过滤器警告()。

    • DeprecationWarning 和 PendingDeprecationWarning 以及 ImportWarning 被忽略。
    • BytesWarning 将被忽略,除非 -b 选项给出一次或两次;在这种情况下,此警告要么打印(-b)要么变成 例外 (-bb)。

    默认情况下,DeprecationWarning 被忽略。您可以使用以下方法更改过滤器:

    warnings.simplefilter('always', DeprecationWarning)
    

    现在应该打印您的警告:

    >>> import warnings
    >>> warnings.simplefilter('always', DeprecationWarning)
    >>> warnings.warn('test', DeprecationWarning)
    /home/guest/.env/bin/ipython:1: DeprecationWarning: test
      #!/home/guest/.env/bin/python
    

    【讨论】:

    • 我明白了。我不确定我是否同意在 2.7 中将其从响亮改为不响亮的决定。默认情况下,用户应该在事情​​发生变化时被告知,这样他们就不会完全不知道。谢谢。
    • @Damgaard:用户不在乎,只要它有效。这是对开发人员的警告,他们无论如何都应该使用-W all-W once 进行测试。
    【解决方案3】:
    $ python -Wall
    Python 2.7.3 (default, Sep 26 2013, 20:03:06) 
    [GCC 4.6.3] on linux2
    Type "help", "copyright", "credits" or "license" for more information.
    >>> import warnings
    >>> warnings.warn("test", DeprecationWarning)
    __main__:1: DeprecationWarning: test
    

    【讨论】:

      猜你喜欢
      • 2011-01-03
      • 2021-06-03
      • 2018-12-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-27
      • 1970-01-01
      相关资源
      最近更新 更多