如何从Python函数截获多个警告?

2024-06-28 19:53:17 发布

您现在位置:Python中文网/ 问答频道 /正文

这里有一些Python伪代码来说明一个问题(我使用的是Python 3.8,但我怀疑这有多重要):

import warnings
from some_library import function, LibraryWarning  # (a library that I do not control)

warning_log = []
with warnings.catch_warnings():
    warnings.simplefilter("error")
    try:
        result = function()
    except LibraryWarning as w:
        warning_log.append(w)
        with warnings.catch_warnings():
            warnings.simplefilter("ignore")
            result = function()

这段代码的主要目的是生成result,而不会在屏幕上出现任何杂乱的警告。它实现了这一点。但是,我还想记录发生的任何警告,以供以后查看。如果function()只生成一个警告,那么这段代码也可以实现这一点。但是,有时function()会产生两个警告。由于我必须切换到忽略警告以获取result,因此我从未看到第二个警告,也无法将其附加到日志中

我如何对生成的所有警告进行完整核算,同时仍能获得最终结果 结果如何

谢谢你的建议


Tags: 代码fromimportlog警告withlibraryfunction
1条回答
网友
1楼 · 发布于 2024-06-28 19:53:17
def a_warning_function():
 warning_log = []
 with warnings.catch_warnings():
     warnings.simplefilter("error")
     try:
        result = function()
        return result
    except LibraryWarning as w:
        warning_log.append(w)
        with warnings.catch_warnings():
            warnings.simplefilter("ignore")
            result = function()
            return result 

相关问题 更多 >