Sphinx无法导入根目录test模块的文档生成问题
我配置了root_dir/docs/source/conf.py,可自动为root_dir/src和root_dir/test目录下的.py文件生成.rst文档,但引用root_dir/test下的测试文件时遇到导入问题。
仓库结构
src/pythontemplate/__main__.py src/pythontemplate/helper.py test/test_adder.py docs/source/conf.py
构建警告
执行cd docs && make html构建文档时,出现以下警告:
WARNING: Failed to import pythontemplate.test.test_adder. ... WARNING: autodoc: failed to import module 'test.test_adder' from module 'pythontemplate'; the following exception was raised: No module named 'pythontemplate.test'
项目设计背景
项目特意将test目录放在根目录而非src下,命名为test而非tests,这样pip install -e .生成的tar.gz包会包含test目录,但whl包不会,符合需求。
自动生成的RST内容
自动生成的root_dir/docs/source/autogen/test/test_adder.rst内容如下:
.. _test_adder-module: test_adder Module ================= .. automodule:: test.test_adder :members: :undoc-members: :show-inheritance:
尝试改为.. automodule:: pythontemplate.test.test_adder也无法成功导入。
已知错误原因是test目录不在pythontemplate的pip包中,这是设计选择。现需解决:如何在不将test加入pip包的前提下,让Sphinx从自动生成的.rst文件中正确引用root_dir/test下的test_*.py文件并完成导入?
解决方案
1. 修改Sphinx配置添加模块搜索路径
在docs/source/conf.py中,将项目根目录和test目录添加到Python的模块搜索路径,让Sphinx能找到test下的模块:
import os import sys # 添加项目根目录到路径 sys.path.insert(0, os.path.abspath('../../')) # 直接添加test目录到路径 sys.path.insert(0, os.path.abspath('../../test'))
2. 调整RST文件的模块引用格式
将自动生成的RST文件里的.. automodule:: test.test_adder改为.. automodule:: test_adder——因为test目录已加入Python路径,直接引用模块名即可。
3. 优化sphinx-apidoc生成命令(可选)
如果用sphinx-apidoc自动生成RST,执行命令时指定test目录的上级路径,避免生成带test.前缀的模块引用:
sphinx-apidoc -o docs/source/autogen/test ../test
这样生成的RST会直接使用test_adder作为模块名,无需手动修改。
注意事项
- Python 3支持命名空间包,不需要给test目录添加
__init__.py;若要兼容旧版本Python,可添加一个空的__init__.py文件。 - 确保已执行
pip install -e .安装项目开发依赖,避免导入src下模块时出现问题。
内容的提问来源于stack exchange,提问作者a.t.

