[英]Is it possible to capture all warnings raised in a try block in python?
I have some code that's schematically along the lines of:我有一些代码示意性地沿着以下几行:
from logging import warning
def complex_function():
# Do some stuff
raise Warning("blah")
# Do some more stuff
raise Warning("Blah again")
try:
complex_function()
except Warning as e:
warning(e)
This results in:这导致:
WARNING:root:blah
I would like to catch all warnings raised, and log them.我想捕捉所有提出的警告,并记录它们。 In my code, such warnings sometimes come from 3rd party libraries, so it is not practical to modify the warnings in place to use
logging.warning
, and I also want to store the warning information so that I can return some version of that information via an API.在我的代码中,此类警告有时来自 3rd 方库,因此修改警告以使用
logging.warning
是不切实际的,而且我还想存储警告信息,以便我可以通过以下方式返回该信息的某个版本一个 API。
Is there a way for me to do something like this that catches all warnings, and loops over them?有没有办法让我做这样的事情来捕捉所有警告并循环它们?
Too late, I'm realising that I'm raising warnings wrong in the example above, and complex_function
should be something long the lines of:太晚了,我意识到我在上面的示例中提出了错误的警告,并且
complex_function
应该是以下complex_function
行:
def complex_function():
# Do some stuff
warnings.warn("blah")
# Do some more stuff
warnings.warn("Blah again", UnknownWarningType)
And I think I can catch these with warnings.catch_warnings
我想我可以用
warnings.catch_warnings
来捕捉这些
Were you expecting something like the following:您是否期待以下内容:
import warnings
warnings.filterwarnings('error')
def warning_func():
print('hello')
warnings.warn(Warning('Warn1'))
print('hi')
warnings.warn(Warning('Warn2'))
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
warning_func()
print(w)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.