简体   繁体   English

是否可以捕获在 python 中的 try 块中引发的所有警告?

[英]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?有没有办法让我做这样的事情来捕捉所有警告并循环它们?

edit编辑

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.

相关问题 如何检测是否从python中的try块引发了异常? - How to detect if an exception has been raised from a try block in python? python try除了不能捕获所有错误 - python try except does not capture all errors 是否可以在python的try块中添加超时 - Is it possible to add a timeout in try block in python 只有当在 try/except 块中引发任何异常时,python 中有没有办法执行一段代码? - Is there a way in python to execute a piece of code only if any exception is raised in a try/except block? 在尝试块中引发错误后,使 python 不撤消操作 - Make python don't undo things after an error is raised in try block 在python中,是否可能在调用之后但紧随其后的try块之前发生异常? - in python, is it possible for an exception to occur after a call but “before” the try block that follows it? Python:try块可能有多个异常语句吗? - Python: Is it possible to have multiple exceptions statments for a try block? “尝试直到没有异常被引发”的Python习惯用法 - Python idiom for 'Try until no exception is raised' 即使在引发异常的情况下,继续在Python中的try子句中 - Continue in a try clause in Python, even if the exception is raised try-except 块:如果引发异常,则类似于“else” - try-except block: analogue for 'else' if exception was raised
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM