python - 构建sphinx文档时导入模块失败

标签 python python-sphinx

我使用的是 Sphinx 版本 1.4.5

我的项目结构如下:

+ src > main.py + 文档(使用 sphinx-quickstart 生成)

即使在 docs/conf.py 中添加 src 文件夹的路径后:

sys.path.insert(0, os.path.abspath('../src'))

并为 src/main.py 生成第一个文件(即 docs/src.rstdocs/modules.rst) :

$ sphinx-apidoc -fo docs src

当我尝试使用以下内容构建 html 网页时:

$ make clean
$ make html

它找不到 src 模块和 src/main.py:

警告:autodoc:无法导入模块 u'src.main';引发了以下异常

最佳答案

我喜欢在 conf.py 中使用以下代码来准确了解当前目录是什么以及目标模块在哪里(以获取文档):

current_dir = os.path.dirname(__file__)
target_dir = os.path.abspath(os.path.join(current_dir, "../../src"))
sys.path.insert(0, target_dir)

print(target_dir)

在本例中,我希望为我的 src 创建文档,请参阅上下文树:

main
├── docs
│   ├── build
│   ├── make.bat
│   ├── Makefile
│   └── source
│       ├── conf.py
│       └── index.rst
│ 
└── src
    ├── __init__.py
    ├── target_module
    ├── requirements.txt
    └── setup.py

接下来,从您的终端:

[user@localhost docs]$ sphinx-apidoc -f -o source/ ../src/target_module
[user@localhost docs]$ make html

关于python - 构建sphinx文档时导入模块失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38963631/

相关文章:

python - 将字典转换为字符串

python - 从 Sphinx 中的 .rst 格式的文件导入多个表

python - 如何引用在我自己的 sphinx 扩展中生成的自定义索引?

python - 如何在 Pandas 的开头和结尾添加零值?

python - 如何最好地实现一个只能调用一次 setter 的属性?

python - "Value Error: x and y must be same size"错误。多元线性回归

python - 使 View 代码显示模块源

python - 从 Sphinx 文档中删除单词 "module"

python - 代码块中的 Sphinx 变量替换

python - 傅里叶空间滤波