如何获取警告。警告发出警告而不忽略行?

2024-05-12 20:24:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图提出一个DeprecationWarning,其中包含基于文档中所示示例的代码片段。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。文件没有提到忽略的标准。发出消息,发出警告。警告正确地发出Userwarning.

是什么导致了这种情况?我如何得到警告才能真正发出警告?


Tags: 代码文档orgnonehttp警告示例docs
3条回答

警告模块实现基于特定条件的警告筛选。您可以通过打印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在默认情况下被忽略。您可以使用^{}模块中的函数和^{} command-line optionto 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
$ 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

从文档中:

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).

默认情况下,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

相关问题 更多 >