构建 sphinx 文档时导入模块失败
Failed to import module when building the sphinx documentation
我正在使用 Sphinx
版本 1.4.5
。
我的项目结构如下:
+ src > main.py
+ docs (generated with sphinx-quickstart)
即使在 docs/conf.py
中添加 src
文件夹的路径后:
sys.path.insert(0, os.path.abspath('../src'))
并为 src/main.py
(即 docs/src.rst
和 docs/modules.rst
)生成第一个文件:
$ sphinx-apidoc -fo docs src
当我尝试构建 html
网页时:
$ make clean
$ make html
找不到 src
模块和 src/main.py
:
WARNING: autodoc: failed to import module u'src.main'; the following exception was raised
您当前的工作目录应该是您的 makefile 的目录,它应该是 docs
。
尝试为您的路径插入执行此操作:
sys.path.insert(0, os.path.abspath('../'))
另外考虑一个比 src
更好的目录名。
我喜欢在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
我正在使用 Sphinx
版本 1.4.5
。
我的项目结构如下:
+ src > main.py
+ docs (generated with sphinx-quickstart)
即使在 docs/conf.py
中添加 src
文件夹的路径后:
sys.path.insert(0, os.path.abspath('../src'))
并为 src/main.py
(即 docs/src.rst
和 docs/modules.rst
)生成第一个文件:
$ sphinx-apidoc -fo docs src
当我尝试构建 html
网页时:
$ make clean
$ make html
找不到 src
模块和 src/main.py
:
WARNING: autodoc: failed to import module u'src.main'; the following exception was raised
您当前的工作目录应该是您的 makefile 的目录,它应该是 docs
。
尝试为您的路径插入执行此操作:
sys.path.insert(0, os.path.abspath('../'))
另外考虑一个比 src
更好的目录名。
我喜欢在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