如何让多层级Python项目中sphinx仅用文件名作为模块标题
实现Sphinx接口文档无路径前缀展示的配置方法
前置检查
首先确认你的docs/conf.py中已经正确添加了源码根目录到Python搜索路径,在文件开头加入以下代码:
import os import sys sys.path.insert(0, os.path.abspath('../src'))
方案一:修改原生sphinx-apidoc配置
1. 调整Sphinx核心配置
在conf.py中添加以下配置,关闭全局模块前缀展示:
# 关闭类、方法前的模块路径前缀 add_module_names = False
2. 自定义apidoc生成模板
sphinx-apidoc支持使用自定义Jinja模板生成rst文件,直接修改标题生成规则,去除路径前缀:
- 在
docs目录下新建_templates/apidoc文件夹 - 新建
package.rst模板文件,内容如下:
{{ fullname.split('.')[-1] }} {{ '=' * fullname.split('.')[-1]|length }} .. automodule:: {{ fullname }} {% if modules %} .. rubric:: 子模块 .. autosummary:: :toctree: :recursive: {% for item in modules %} {{ item }} {% endfor %} {% endif %} {% if members %} .. rubric:: 模块内容 {% for item in members %} .. autofunction:: {{ item }} {% endfor %} {% endif %}
- 新建
module.rst模板文件,内容如下:
{{ fullname.split('.')[-1] }} {{ '=' * fullname.split('.')[-1]|length }} .. automodule:: {{ fullname }} {% if functions %} .. rubric:: 函数 {% for item in functions %} .. autofunction:: {{ item }} {% endfor %} {% endif %} {% if classes %} .. rubric:: 类 {% for item in classes %} .. autoclass:: {{ item }} :members: :undoc-members: :show-inheritance: {% endfor %} {% endif %}
3. 修改buildapi命令
在Makefile的buildapi命令中添加模板路径参数:
buildapi: sphinx-apidoc -fMeET ../src -o api --templatedir _templates/apidoc @echo "Auto-generation of api documentation finished. " \ "The generated files are in 'api/'"
方案二:使用sphinx-autoapi扩展(更简便,推荐)
原生sphinx-apidoc灵活度较低,推荐使用第三方扩展sphinx-autoapi,无需手动维护模板即可实现需求:
- 安装扩展:
pip install sphinx-autoapi
- 在
conf.py中添加扩展和对应配置:
extensions = [ # 保留原有其他扩展,新增以下内容 'autoapi.extension', ] # autoapi基础配置 autoapi_type = 'python' autoapi_dirs = ['../src'] autoapi_options = ['members', 'undoc-members', 'show-inheritance', 'show-module-summary'] add_module_names = False
- 移除原有buildapi相关配置和
api.rst中的glob规则,直接在需要插入API文档的位置引入即可,扩展会自动生成无前缀的层级目录。
内容的提问来源于stack exchange,提问作者Farhood ET
相关产品推荐
相关产品推荐

