You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何捕获Python库中logging.warning()发出的警告?

问题

调用Qsc函数传入特定参数时,会触发如下警告:

Newton solve did not get close to desired tolerance. Final residual: 1.7380027083030736e-09

该警告由库内logger.warning('Newton solve did not get close to desired tolerance. 'f'Final residual: {last_residual_norm}')代码触发。

希望在不修改库代码的前提下捕获该警告,对结果做特殊处理。尝试了以下代码:

import logging
import warnings
from qsc import Qsc

logging.captureWarnings(True)

with warnings.catch_warnings(record=True) as w:
    stel = Qsc(rc=[1, 0.20990165844612937], zs=[0, -0.008780473233288922], nfp=2, etabar=-1.699682124042855)
    warnings.warn("warn from warning")
    logging.warn("warn from logging")
    logging.warning("warning from logging")
    if w:
        for warning in w:
            logging.warning(str(warning.message))
            print("warning was captured\n")

但仅捕获到warnings.warn()发出的警告,输出结果如下:

Newton solve did not get close to desired tolerance. Final residual: 1.7380027083030736e-09
WARNING:root:warning from logging
WARNING:root:warn from warning
warning was captured

解决方法

核心原因:库代码用的是logging模块输出警告,而非warnings模块,所以warnings.catch_warnings无法捕获这类信息。可以通过自定义日志处理器来拦截并记录特定日志:

  • 定义自定义日志处理器类,用于筛选并捕获目标警告:
import logging
from qsc import Qsc

class WarningCaptureHandler(logging.Handler):
    def __init__(self):
        super().__init__()
        self.captured_warnings = []
    
    def emit(self, record):
        # 匹配目标警告的特征文本
        if "Newton solve did not get close to desired tolerance" in record.getMessage():
            self.captured_warnings.append(record.getMessage())
  • 将处理器绑定到库对应的日志器,执行调用后再移除(避免影响后续日志逻辑):
# 获取库中newton模块使用的日志器
logger = logging.getLogger("qsc.newton")
# 创建并添加自定义处理器
capture_handler = WarningCaptureHandler()
logger.addHandler(capture_handler)

# 执行Qsc调用
stel = Qsc(rc=[1, 0.20990165844612937], zs=[0, -0.008780473233288922], nfp=2, etabar=-1.699682124042855)

# 移除处理器,避免干扰其他日志输出
logger.removeHandler(capture_handler)

# 处理捕获到的警告
if capture_handler.captured_warnings:
    for warn_msg in capture_handler.captured_warnings:
        print(f"捕获到目标警告:{warn_msg}")
        # 在这里添加你的特殊处理逻辑,比如标记结果、重试计算等
  • 补充:如果不确定日志器名称,可以临时遍历所有日志器确认,或者直接给根日志器添加处理器(但需要更严格的文本筛选,避免捕获无关日志)。

内容的提问来源于stack exchange,提问作者João Cândido

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 05:37:19