sách gpt4 ăn đã đi

python — Làm cách nào để cảnh báo.warn phát ra cảnh báo mà không bỏ qua dòng này?

In lại Tác giả: IT Lão Cao 更新时间:2023-10-28 20:32:49 28 4
mua khóa gpt4 giày nike

我正在尝试提出一个 DeprecationWarning,其中包含基于文档中显示的示例的代码片段。 http://docs.python.org/2/library/warnings.html#warnings.warn

官方

def deprecation(message):
warnings.warn(message, DeprecationWarning, stacklevel=2)

của tôi

import warnings
warnings.warn("This is a warnings.", DeprecationWarning, stacklevel=2) is None # returns True

我尝试删除 stacklevel 参数,将其设置为负数、0、2 和 20000。警告总是被默默吞下。它不会发出警告或引发异常。它只是忽略该行并返回 Không có。文档没有提到忽略的标准。发出消息,使 warnings.warn 正确发出 Userwarning.

什么可能导致这种情况,我如何得到警告以实际发出警告?

câu trả lời hay nhất

来自文档:

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/

28 4 0
Chứng chỉ ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com
Xem sitemap của VNExpress