如何从不同的包中导入 python 个模块

how to import python modules from different packages

我有一个 python 应用程序,其中也包含单元测试。下面是我的文件结构

├── src
│   ├── common
│   │    ├──constants.py
│   │    └──configs.py
│   ├── utils
│   │    ├──module1.py
│   │    └──module2.py
│   └── service
│   │     ├──module3.py
│   │     └──module4.py
│   └── main.py
├── test
│   ├── utils
│   │    ├──test_module1.py
│   │    └──test_module2.py

utils/module1.py 包含

# module1.py
from common.constants import LOG_FORMAT, TIME_FORMAT
...

test_module1.py包含

# test_module1.py
import sys
sys.path.append(".")
from src.utils.module1 import filter_file
from unittest import TestCase, main, mock

并且当我 运行 下面的代码来自 root 下面的异常时发生。

$- python3 test/utils/test_module1.py
$- ModuleNotFoundError: No module named 'common'

我正在使用 linux 机器。当我尝试添加“src”时它会起作用。在 module1.py 中的每个模块导入之前。但是我不想更改 src 中的代码,因为我已经对它进行了 dockerized。请提出您的想法。

您正在将包含 testsrc 的目录附加到 sys.path,然后使用 src.utils.module1 访问 topleveldir/src/utils/module1.py。该模块尝试导入文件 topleveldir/common/constants.py,但该文件实际上位于 topleveldir/src/common/constants.py - 此 必须 给出 ModuleNotFound 错误。将 sys.path.append(".") 更改为 sys.path.append("./src") 并从下面的导入中删除 src.,它应该可以正常工作。