如何控制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/generatedclasses.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的参数来统一生成文件的存储路径,具体操作如下:
- 修改
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
- 在各
.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/目录下,和期望的结构一致。
- 构建前的清理与验证
- 删除之前生成的零散
generated文件夹,避免残留文件干扰; - 执行构建命令确认配置生效:
sphinx-build -b html doc doc/_build/html
内容的提问来源于stack exchange,提问作者Mathieu
相关产品推荐
相关产品推荐

