本文介绍了在Python中,如何捕获警告,就像是异常一样?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在我的python代码中使用的第三方库(以C编写)正在发出警告。我想要使用 try
除了
语法以正确处理这些警告。有没有办法这样做?
A third-party library (written in C) that I use in my python code is issuing warnings. I want to be able to use the try
except
syntax to properly handle these warnings. Is there a way to do this?
推荐答案
引用python手册():
To quote from the python handbook (27.6.4. Testing Warnings):
import warnings
def fxn():
warnings.warn("deprecated", DeprecationWarning)
with warnings.catch_warnings(record=True) as w:
# Cause all warnings to always be triggered.
warnings.simplefilter("always")
# Trigger a warning.
fxn()
# Verify some things
assert len(w) == 1
assert issubclass(w[-1].category, DeprecationWarning)
assert "deprecated" in str(w[-1].message)
(编辑:固定的例子,是一个部分关闭)
(edit: fixed example, was a section off)
这篇关于在Python中,如何捕获警告,就像是异常一样?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!