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

问题描述 投票:1回答:1

我有一些代码,它们的示意图如下:

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) 

这导致:

WARNING:root:blah

我想抓住所有提出的警告,并记录下来。在我的代码中,这样的警告有时来自第三方库,因此修改使用logging.warning的警告是不切实际的,我还想存储警告信息,以便我可以通过API返回该信息的某些版本。

有没有办法让我做这样的事情来捕获所有警告,并循环它们?

编辑

太晚了,我意识到我在上面的例子中提出了错误的警告,并且complex_function应该是以下几行:

def complex_function():
    # Do some stuff
    warnings.warn("blah") 
    # Do some more stuff
    warnings.warn("Blah again", UnknownWarningType)

我想我可以用warnings.catch_warnings来捕捉这些

python exception logging warnings
1个回答
2
投票

您是否期望以下内容:

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)
© www.soinside.com 2019 - 2024. All rights reserved.