导入在文件夹内不起作用(找不到模块/导入错误)

问题描述 投票:0回答:1

我在很多页面和这里都看到过这个问题,但我已经尝试了一切,但似乎无法使其发挥作用,所以我需要第二个意见:(

我的代码中有以下结构: project structure 看起来像这样:

ODS/
|__init__.py
|example.py
├── mqtt_model/
│   ├── __init__.py
│   └── mqtt_model.py
└── python-can/
    ├── can-venv/
    ├── __init__.py
    ├── Dockerfile
    ├── mqtt_can_logger.py
    ├── read.py
    ├── requirements.txt
    └── write.py

我想要做的是将 mqtt_class.py 中的类(MQTT_Model)导入到 mqtt_can_logger.py

在我的 mqtt_model/init.py 中我有

from .mqtt_class import MQTT_Model

python_can/init.py 是一个空文件,我想将 MQTT_Model 导入到 mqtt_can_logger.py。

此导入不起作用,但在 example.py 中它确实可以与

from mqtt_model import MQTT_Model
一起使用 它只是在 python_can 目录中不起作用!

我尝试过做相对和绝对路径,例如:

from mqtt_model.mqtt_model.mqtt_class import MQTT_Model
from .mqtt_model.mqtt_class import MQTT_Model

from ..mqtt_model import MQTT_Model
from .mqtt_model import MQTT_Model
from mqtt_model import MQTT_Model

什么都不起作用;(我不断收到I mport Error: attemptsrelative import with noknownparent package或ModuleNotFound: no module named 'mqtt_model'

python import importerror modulenotfounderror
1个回答
0
投票

编辑: 我假设您的导入问题是由于从

can-venv
文件夹中创建的虚拟环境运行程序引起的。因此,
python-can
文件夹成为项目的根文件夹。它使解释器无法找到该目录之外的模块和包。要解决此问题,您应该在
ODS/
文件夹中为您的项目重新创建虚拟环境,或者按照此
sys.path.insert
添加额外的路径 answer:

import sys

sys.path.insert(1, '/path/to/ODS/')

# OR

sys.path.insert(1, '/path/to/ODS/mqtt_model')

然后,您可以从

ODS/
文件夹导入模块和包:

from mqtt_model import mqtt_class

model = mqtt_class.MQTT_Model(...)  # sys.path.insert(1, '/path/to/ODS/')

# OR

from mqtt_class import MQTT_Model   # sys.path.insert(1, '/path/to/ODS/mqtt_model')
© www.soinside.com 2019 - 2024. All rights reserved.