cuốn sách gpt4 ai đã làm

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

In lại Tác giả: Vũ trụ không gian 更新时间:2023-11-03 20:32:45 29 4
mua khóa gpt4 Nike

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

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

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

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

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

29 4 0
không gian vũ trụ
Hồ sơ

Tôi là một lập trình viên xuất sắc, rất giỏi!

Nhận phiếu giảm giá taxi Didi miễn phí
Phiếu giảm giá taxi Didi
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