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

如何在Sphinx扩展的警告信息中添加文档行号?

Sphinx内联图标扩展警告添加文档行号解决方案

问题背景

开发Sphinx内联图标扩展时,抛出的警告未包含文档路径和行号,增加调试难度:

  • 当前警告格式:
WARNING: icon "sync" is not part of fontawesome
  • 期望警告格式:
path/to/file.rst:10: WARNING: icon "sync" is not part of fontawesome

当前代码

def visit_icon_node_html(translator: SphinxTranslator, node: icon_node) -> None:
    """Visit the html output."""
    font, glyph = get_glyph(node["icon"])
    translator.body.append(f'<i class="{Fontawesome.html_font[font]} fa-{glyph}">')

    return

def get_glyph(text) -> Tuple[str, str]:
    """Get the glyph from text.

    Args:
        text: The text to transform (e.g. "fas fa-folder")

    Returns:
        (glyph, font): from the provided text. skip the node if one of them does not exist
    """
    # split the icon name to find the name inside
    m = re.match(Fontawesome.regex, text)
    if not m:
        logger.warning(f'invalid icon name: "{text}"')
        raise nodes.SkipNode
    if m.group("font") not in Fontawesome.html_font:
        logger.warning(f'font "{m.group("font")}" is not part of fontawesome')
        raise nodes.SkipNode
    if m.group("glyph") not in Fontawesome.metadata:
        logger.warning(f'icon "{m.group("glyph")}" is not part of fontawesome')
        raise nodes.SkipNode

解决方案

给get_glyph函数添加node参数,在调用logger.warning时传递location=node参数即可。Sphinx的节点对象包含源文件路径、行号等元数据,logger会自动解析这些信息并添加到警告输出中。

修改后的代码

def visit_icon_node_html(translator: SphinxTranslator, node: icon_node) -> None:
    """Visit the html output."""
    # 传递node参数给get_glyph
    font, glyph = get_glyph(node["icon"], node)
    translator.body.append(f'<i class="{Fontawesome.html_font[font]} fa-{glyph}">')

    return

def get_glyph(text, node) -> Tuple[str, str]:
    """Get the glyph from text.

    Args:
        text: The text to transform (e.g. "fas fa-folder")
        node: The Sphinx node object, used for warning location info

    Returns:
        (glyph, font): from the provided text. skip the node if one of them does not exist
    """
    # split the icon name to find the name inside
    m = re.match(Fontawesome.regex, text)
    if not m:
        logger.warning(f'invalid icon name: "{text}"', location=node)
        raise nodes.SkipNode
    if m.group("font") not in Fontawesome.html_font:
        logger.warning(f'font "{m.group("font")}" is not part of fontawesome', location=node)
        raise nodes.SkipNode
    if m.group("glyph") not in Fontawesome.metadata:
        logger.warning(f'icon "{m.group("glyph")}" is not part of fontawesome', location=node)
        raise nodes.SkipNode

说明

  • Sphinx的logger.warning方法支持location参数,接收节点对象后会自动提取对应源文件的路径和行号,添加到警告信息前。
  • 从visit_icon_node_html函数传递node到get_glyph,就能让警告关联到具体文档位置,降低调试成本。

内容的提问来源于stack exchange,提问作者Pierrick Rambaud

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 05:22:40