我如何让 warnings.warn 发出警告而不是忽略该行? [英] How do I get warnings.warn to issue a warning and not ignore the line?

查看:111
本文介绍了我如何让 warnings.warn 发出警告而不是忽略该行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用基于文档中显示的示例的代码片段提出 DeprecationWarning.http://docs.python.org/2/library/warnings.html#warnings.warn

官方

def 弃用(消息):警告.警告(消息,弃用警告,堆栈级别= 2)

我的

导入警告warnings.warn("这是一个警告.", DeprecationWarning, stacklevel=2) is None # 返回 True

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

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

解决方案

来自文档:

<块引用>

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

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

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

warnings.simplefilter('always', DeprecationWarning)

现在应该打印您的警告:

<预><代码>>>>进口警告>>>warnings.simplefilter('always', DeprecationWarning)>>>warnings.warn('test', DeprecationWarning)/home/guest/.env/bin/ipython:1: DeprecationWarning: 测试#!/home/guest/.env/bin/python

I'm trying to raise a DeprecationWarning, with a code snippet based on the example shown in the docs. http://docs.python.org/2/library/warnings.html#warnings.warn

Official

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

Mine

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

I've tried removing the stacklevel argument, setting it to negative, 0, 2 and 20000. The warning is always silently swallowed. It doesn't issue a warning or raise an exception. It just ignores the line and returns None. The docs doesn't mention the criteria for ignoring. Giving a message, makes warnings.warn correctly issue a Userwarning.

What can be causing this and how do I get warn to actually warn?

解决方案

From the docs:

By default, Python installs several warning filters, which can be overridden by the command-line options passed to -W and calls to filterwarnings().

  • DeprecationWarning and PendingDeprecationWarning, and ImportWarning are ignored.
  • BytesWarning is ignored unless the -b option is given once or twice; in this case this warning is either printed (-b) or turned into an exception (-bb).

By default, DeprecationWarning is ignored. You can change the filters using the following:

warnings.simplefilter('always', DeprecationWarning)

Now your warnings should be printed:

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

这篇关于我如何让 warnings.warn 发出警告而不是忽略该行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆