Error quot;Attempted relative importquot; on Sphinx-doc(尝试在Sphinx-DOC上进行相对导入时出错)
本文介绍了尝试在Sphinx-DOC上进行相对导入时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我尝试使用Sphinx-DOC的自动文档功能。我想解决以下问题。当时,StackOverflow的解决方案都没有奏效。 是由于我的项目结构还是我选择导入模块的方式?
给定的文件结构:
project
|_ src
| |_ pre_processing
| | |_ fileInfo.py
| |
| |_ utils
| |_ folder.py
|_ test
|
|_ doc
| |_ doc_user
| |_ build
| |_ source
| |_config.py
以下配置系统路径:
import os
import sys
sys.path.insert(0, os.path.abspath('../../../src/'))
我在fileInfo.py中有一些相对导入:
from ..utils.folder import get_files_directory
终端错误
WARNING: autodoc: failed to import module 'pre_processing.fileInfo'; the following exception was raised:
Traceback (most recent call last):
File "/home/florian-stage/miniconda/envs/gd/lib/python3.5/site-packages/sphinx/ext/autodoc/importer.py", line 140, in import_module
__import__(modname)
File "/home/florian-stage/Projet-2018/pg_georef_data-master/arbo propre/src/pre_processing/fileInfo.py", line 12, in <module>
from ..utils.folder import get_files_directory
ValueError: attempted relative import beyond top-level package
推荐答案
将项目根目录而不是源目录添加到sys.path似乎可以解决该问题。请记住添加__init__.py
文件以声明包。
之后,您还应该修改*.rst
文件中对模块的引用,将src
作为前缀。
示例:
# in "doc/doc_user/source/config.py"
import os
# ("../../..") instead of ("../../../src")!
sys.path.insert(0, os.path.abspath("../../.."))
__init__.py
中的样例定义
# in "src/utils/__init__.py"
from .folder import get_files_directory
在文件信息中导入。可能会有所不同,具体取决于您将get_files_directory
导入__init__.py
的方式或是否将其导入。
# in "src/pre_processing/fileInfo.py"
from ..utils import get_files_directory
任何*.rst
文件中的引用应如下所示。(前缀src
)
.. automodule:: src.pre_processing.fileInfo
:members:
project
├── src
│ ├── __init__.py
│ ├── ...
│ ├── pre_processing
│ ├── __init__.py
│ ├── fileInfo.py
│ └── utils
│ ├── __init__.py
│ └── folder.py
├── test
├── doc
│ └── doc_user
│ ├── build
│ └── source
│ ├── config.py
│ └── ...
另一个使用单一目录存储Shinx文档的示例。
# in "docs/conf.py"
import os
# ("..") instead of ("../src")!
sys.path.insert(0, os.path.abspath(".."))
project
├── src
├── test
├── docs
│ ├── _static
│ ├── _templates
│ ├── ...
│ ├── index.rst
│ └── conf.py
├── ...
├── setup.cfg
└── setup.py
引用
- The import system
- Python Modules and Packages – An Introduction
- Implicit Namespace Packages
这篇关于尝试在Sphinx-DOC上进行相对导入时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
沃梦达教程
本文标题为:尝试在Sphinx-DOC上进行相对导入时出错


基础教程推荐
猜你喜欢
- 如何在 Python 中检测文件是否为二进制(非文本)文 2022-01-01
- 将 YAML 文件转换为 python dict 2022-01-01
- 合并具有多索引的两个数据帧 2022-01-01
- 使用 Google App Engine (Python) 将文件上传到 Google Cloud Storage 2022-01-01
- 哪些 Python 包提供独立的事件系统? 2022-01-01
- 如何在Python中绘制多元函数? 2022-01-01
- Python 的 List 是如何实现的? 2022-01-01
- 使用Python匹配Stata加权xtil命令的确定方法? 2022-01-01
- 使 Python 脚本在 Windows 上运行而不指定“.py";延期 2022-01-01
- 症状类型错误:无法确定关系的真值 2022-01-01