Dam*_*ard 23 python warnings suppress-warnings python-2.7
我正在尝试DeprecationWarning使用基于文档中显示的示例的代码段来引发一个.http://docs.python.org/2/library/warnings.html#warnings.warn
官方
def deprecation(message):
warnings.warn(message, DeprecationWarning, stacklevel=2)
Run Code Online (Sandbox Code Playgroud)
矿
import warnings
warnings.warn("This is a warnings.", DeprecationWarning, stacklevel=2) is None # returns True
Run Code Online (Sandbox Code Playgroud)
我已经尝试删除stacklevel参数,将其设置为负数,0,2和20000.警告总是被静默吞下.它不会发出警告或引发异常.它只是忽略了线和返回None.文档没有提到忽略的标准.发送消息,使warnings.warn正确发出一个Userwarning.
可能导致这种情况的原因以及如何警告实际发出警告?
Mac*_*Gol 30
来自文档:
默认情况下,Python会安装几个警告过滤器,这些过滤器可以被传递给-W的命令行选项覆盖并调用filterwarnings().
- DeprecationWarning和PendingDeprecationWarning以及ImportWarning将被忽略.
- 除非给出一次或两次-b选项,否则忽略BytesWarning; 在这种情况下,此警告可以打印(-b)或转换为异常(-bb).
默认情况下,将DeprecationWarning被忽略.您可以使用以下内容更改过滤器:
warnings.simplefilter('always', DeprecationWarning)
Run Code Online (Sandbox Code Playgroud)
现在你的警告应该打印出来:
>>> import warnings
>>> warnings.simplefilter('always', DeprecationWarning)
>>> warnings.warn('test', DeprecationWarning)
/home/guest/.env/bin/ipython:1: DeprecationWarning: test
#!/home/guest/.env/bin/python
Run Code Online (Sandbox Code Playgroud)
警告模块根据特定条件实施警告过滤.您可以通过打印显示默认过滤器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)]
Run Code Online (Sandbox Code Playgroud)
如您所见,DeprecationWarning默认情况下会被忽略.您可以使用warnings模块中的函数和Python 的-W命令行选项来配置过滤器 - 有关详细信息,请参阅文档.
例:
$ 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
Run Code Online (Sandbox Code Playgroud)