我正在尝试使用基于文档中显示的示例的代码片段来提出DeprecationWarning
. http://docs.python.org/2/library/warnings.html#warnings.warn
官方
def deprecation(message):
warnings.warn(message, DeprecationWarning, stacklevel=2)
我的
cảnh báo nhập khẩu
warnings.warn("This is a warnings.", DeprecationWarning, stacklevel=2) is None # returns True
我尝试删除 stacklevel 参数,将其设置为负数、0、2 和 20000。警告总是被默默地吞下。它不会发出警告或引发异常。它只是忽略该行并返回 Không có
。该文档没有提及忽略的标准。发出消息,使 warnings.warn 正确发出Userwarning。
什么可能导致此问题以及如何让警告真正发出警告?
Từ tài liệu:
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
Tôi là một lập trình viên xuất sắc, rất giỏi!