如何在python3中从另一个包导入模块



目前我的文件结构如下。

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

我的test_module1.py包括

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

utils/module1.py包括

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

在这里,当我尝试从root运行test_module1.py文件时,我收到一个错误,说

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

有什么问题

对其进行了测试,在Windows:上的工作方式如下

├── src
│   └── utils
│        └──lib.py
├── test
│   └── utils
│        └──bla.py

lib.py:

def test():
print("woo")

bla.py:

import os
import sys
sys.path.append(".." + os.sep + "..")
from src.utils.lib import test
test()

最新更新