gpt4 book ai didi

python - 如何让 warnings.warn 发出警告而不忽略该行?

转载 作者:太空宇宙 更新时间:2023-11-03 20:32:45 29 4
gpt4 key购买 nike

我正在尝试使用基于文档中显示的示例的代码片段来提出DeprecationWarninghttp://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。

什么可能导致此问题以及如何让警告真正发出警告?

最佳答案

来自文档:

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

关于python - 如何让 warnings.warn 发出警告而不忽略该行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57380214/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com