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

Is it possible to capture all warnings raised in a try block in python?

我有一些代码大致如下:

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

我想捕获所有发出的警告,并将它们记录下来。在我的代码中,此类警告有时来自 3rd 方库,因此将警告修改为使用 logging.warning 是不切实际的,我还想存储警告信息以便我可以 return该信息的某个版本通过 API.

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

编辑

为时已晚,我意识到我在上面的示例中发出了错误的警告,complex_function 应该是以下几行:

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

而且我想我可以用 warnings.catch_warnings

捕捉到这些

您是否期待以下内容:

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)