gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 20:32:49 27 4
gpt4 key购买 nike

我正在尝试提出一个 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。文档没有提到忽略的标准。发出消息,使 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/20960110/

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