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

Sphinx-Gallery生成的Notebook文本块中Sphinx角色与指令无法正常渲染链接

Sphinx-Gallery生成的Notebook文本块中Sphinx角色与指令无法正常渲染链接

看起来你遇到的核心问题是Sphinx在构建时优先选择了Sphinx-Gallery生成的.ipynb文件,而非对应的.rst文件——后者才会正确解析:class:、:meth:这类Sphinx角色并生成链接。结合你的构建日志和配置,我整理了几个针对性的解决方案:

1. 让Sphinx优先使用Sphinx-Gallery生成的rst文件

你的构建日志里反复出现类似警告:

WARNING: multiple files found for the document "auto_examples/plot_compute_aac": ['auto_examples\plot_compute_aac.ipynb', ... 'auto_examples\plot_compute_aac.rst']

这说明nbsphinx(处理ipynb的扩展)和Sphinx-Gallery的输出产生了冲突,Sphinx最终选了ipynb文件,但ipynb的markdown单元格默认不会解析Sphinx角色。解决方法是在conf.py中添加nbsphinx_exclude_patterns,排除Sphinx-Gallery生成的ipynb文件:

# conf.py中添加
nbsphinx_exclude_patterns = ['auto_examples/*.ipynb']

这样Sphinx就会自动选择对应的rst文件,而rst文件会正常处理所有Sphinx角色和指令。

2. 清理缓存并重新构建

旧的构建缓存可能导致文件残留,影响Sphinx的文件选择逻辑。运行以下命令彻底清理后重新构建:

make clean
make html

3. 优化Sphinx-Gallery配置(可选)

确保Sphinx-Gallery的配置明确生成rst文件,在conf.py的sphinx_gallery_conf中可以添加相关参数,强化rst生成逻辑:

sphinx_gallery_conf = {
    "doc_module": ("my_project",),
    "examples_dirs": "../../examples",
    "gallery_dirs": "auto_examples",
    "reference_url": {"my_project": None},
    # 确保生成rst文件(默认已开启,但显式声明更稳妥)
    "generate_rst": True,
    # 关闭不必要的ipynb生成(如果不需要用户下载notebook)
    "notebook_images": False,
}

4. 解决ReadTheDocs的pandoc版本问题

虽然这可能不是当前链接失效的直接原因,但版本不兼容的pandoc可能引发其他渲染问题。在ReadTheDocs的配置文件.readthedocs.yaml中指定符合要求的pandoc版本:

build:
  os: ubuntu-22.04
  tools:
    python: "3.10"
    pandoc: "2.19.2"  # 选择2.14.2到4.0.0之间的版本

完成以上步骤后,Sphinx应该会正确解析你在例子文本块中使用的Sphinx角色,生成对应的内部/外部链接了。

备注:内容来源于stack exchange,提问作者Thomas Samuel Binns

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.21 14:33:05