gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 01:04:37 25 4
gpt4 key购买 nike

我有一些代码大致如下:

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

我想捕获所有发出的警告并记录它们。在我的代码中,此类警告有时来自第 3 方库,因此修改警告以使用 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 捕获这些内容

最佳答案

您是否期待类似以下内容:

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)

关于python - 是否有可能捕获 python 中 try block 中引发的所有警告?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55488693/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com