提问人:Michael Bonnet 提问时间:11/17/2023 更新时间:11/17/2023 访问量:14
在 Python 中解析本地包导入
Resolving local package imports in Python
问:
我的 repo 目录结构如下(来自 ):$ tree
.
├── src
│ ├── __init__.py
│ └── stuff.py
├── tests
│ ├── __init__.py
│ ├── test_stuff.py
│ ├── test_utils_constants.py
│ └── test_utils_math.py
└── utils
├── __init__.py
└── math.py
src/__init__.py
:
import os
import sys
PROJECT_PATH = os.getcwd()
SOURCE_PATH = os.path.join(
PROJECT_PATH,"src"
)
sys.path.append(SOURCE_PATH)
tests/__init__.py
import os
import sys
PROJECT_PATH = os.getcwd()
SOURCE_PATH = os.path.join(
PROJECT_PATH,"tests"
)
sys.path.append(SOURCE_PATH)
utils/__init__.py
import os
import sys
PROJECT_PATH = os.getcwd()
SOURCE_PATH = os.path.join(
PROJECT_PATH, "utils"
)
sys.path.append(SOURCE_PATH)
由于某种原因,从 in 导入模块并行为不同。tests/
src/
tests/
在 中,我有以下行:tests/test_utils_math.py
from utils.math import Math
在 中,我有以下行:tests/test_utils_constants.py
from utils.math import Constants
和 都是 中的类。当我在顶级存储库目录中运行时,这些导入似乎运行良好,并且没有遇到任何问题。Math
Constants
utils/math.py
python3 -m pytest
在 中,我有以下行:src/stuff.py
from utils.math import Constants
,以使用该类。Constants
我收到一个错误:
Traceback (most recent call last):
File "/home/mbonnet/my_repo/src/stuff.py", line 14, in <module>
from utils.math import Constants
ModuleNotFoundError: No module named 'utils'
我认为这是由于 pytest 和 Python 以不同的方式理解 repo 的结构。不过,我不知道如何解决/更改此问题。
如何让 Python 发现并使用我在目录中其他位置创建的包?
答: 暂无答案
评论
sys.path
的值来正确诊断问题。但正确的方法是在项目中使用相对导入,并作为主源代码的子包,假设它包含程序需要运行的内容。import
utils
src
tests
utils
src
utils
sys.path
sys.path
utils
sys.path
stuff.py
utils