Sphinx Documentation中automodule缩短模块路径相关问题咨询
Sphinx生成文档省略指定模块前缀的可行解决方案
问题根源说明
你之前的方案报错是因为直接将app/orange/routers加入sys.path后,Python会把该目录下的.py文件识别为顶层模块,不再属于app.orange.routers子包,模块内的相对导入语句失去了父包上下文,因此抛出「attempted relative import with no known parent package」错误。
推荐解决方案(无侵入,不修改导入逻辑)
不要调整sys.path指向子目录,保持正常的全路径导入逻辑,通过Sphinx内置配置修改显示名称即可,完全不会破坏原有模块的导入规则:
步骤1:添加项目根目录到Python路径
在docs/conf.py开头加入以下配置,保证Sphinx可以正常导入你的app包:
import os import sys # 将项目根目录加入Python搜索路径 sys.path.insert(0, os.path.abspath('..'))
步骤2:配置模块名裁剪规则
有两种适配场景的配置方式可选:
方式A:全量自动裁剪(适合批量处理router下所有模块)
通过Sphinx事件钩子自动裁剪所有app.orange.routers.前缀,无需手动配置每个模块:
在docs/conf.py中添加以下代码:
def autodoc_process_bases(app, name, obj, options, bases): # 裁剪基类的模块前缀 for i, base in enumerate(bases): base_module = base.__module__ if base_module.startswith('app.orange.routers.'): base.__module__ = base_module[len('app.orange.routers.'):] def autodoc_process_signature(app, what, name, obj, options, signature, return_annotation): # 裁剪函数/类签名的模块前缀 if name.startswith('app.orange.routers.'): new_qualname = name[len('app.orange.routers.'):] return (signature, return_annotation), new_qualname def setup(app): app.connect('autodoc-process-bases', autodoc_process_bases) app.connect('autodoc-process-signature', autodoc_process_signature) # 模块索引页也裁剪对应前缀 modindex_common_prefix = ['app.orange.routers.']
方式B:手动指定映射(适合需要精确控制的场景)
如果你使用的是Sphinx 4.0以上版本,可以用qualname_overrides配置手动指定显示名称:
qualname_overrides = { "app.orange.routers.test.clear": "test.clear", # 可按格式添加其他函数/类的映射,也可写遍历逻辑批量生成 } modindex_common_prefix = ['app.orange.routers.']
步骤3:编写rst文档
直接使用全路径导入模块即可,生成的文档会自动省略前缀:
.. automodule:: app.orange.routers.test :members:
生成的文档中clear()函数会自动显示为test.clear(),符合你的需求。
内容的提问来源于stack exchange,提问作者Amos Tan
相关产品推荐
相关产品推荐

