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

如何控制Sphinx中autodoc生成的.rst文件的存储目录?

问题描述

我的Sphinx文档结构如下:

doc
 |_ _static
 |_ _templates
 |_ api
     |_ index.rst
     |_ classes.rst
     |_ functions.rst
 |_ index.rst
 |_ more_functions.rst
 |_ conf.py

其中classes.rst、functions.rst和more_functions.rst包含需要通过autodoc/autosummary自动生成文档的类与函数。当前构建后,生成的.rst文件存储位置为:

  • more_functions.rst对应的文件存于doc/generated
  • classes.rst和functions.rst对应的文件存于doc/api/generated

请问是否可以控制这些generated文件夹的创建位置?我希望最终得到统一的generated文件夹,结构如下:

doc
 |_ generated
     |_ generated-from-more-functions.rst
     |_ api
         |_ generated-from-api/classes.rst
         |_ generated-from-api/functions.rst
解决方案

完全可以通过配置autosummary的参数来统一生成文件的存储路径,具体操作如下:

  1. 修改conf.py配置
    在conf.py中添加路径配置,确保统一的生成根目录存在:
import os

# 设定统一的generated根目录(基于conf.py所在路径)
AUTOSUMMARY_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), 'generated'))
# 自动创建目录(避免构建时报错)
os.makedirs(AUTOSUMMARY_ROOT, exist_ok=True)

# 开启autosummary自动生成
autosummary_generate = True
autosummary_imported_members = True
  1. 在各.rst文件中指定生成子路径
    通过:toctree:参数为不同的.rst文件指定对应的生成位置:
  • 对于more_functions.rst:

    .. autosummary::
       :toctree: generated/
       :recursive:
    
       # 列出需要生成文档的函数
       your_module.more_functions.func1
       your_module.more_functions.func2
    

    生成的文件会直接存入doc/generated/目录下。

  • 对于api/classes.rst:

    .. autosummary::
       :toctree: generated/api/
       :recursive:
    
       # 列出需要生成文档的类
       your_module.api.classes.Class1
       your_module.api.classes.Class2
    
  • 对于api/functions.rst:

    .. autosummary::
       :toctree: generated/api/
       :recursive:
    
       # 列出需要生成文档的函数
       your_module.api.functions.func_a
       your_module.api.functions.func_b
    

    这两个文件生成的内容会存入doc/generated/api/目录下,和期望的结构一致。

  1. 构建前的清理与验证
  • 删除之前生成的零散generated文件夹,避免残留文件干扰;
  • 执行构建命令确认配置生效:
    sphinx-build -b html doc doc/_build/html
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 15:09:22