英文:
python3 ModuleNotFoundError with my own modules
问题
![结构][1]
我有这个项目的结构。我想在`data/datadownload.py`中像这样导入我的Restaurant类,从`models/restaurant.py`:
```python
from models.restaurant import Restaurant
但我一直得到ModuleNotFoundError: No module named 'models'
。
注意: data和models两个模块都在项目的根目录中。我还尝试通过在根目录中添加__init__.py
来使根目录成为一个模块。
<details>
<summary>英文:</summary>
[![structure][1]][1]
I have this project structure. I want to import my Restaurant class from `models/restaurant.py` in `data/datadownload.py` like this:
from models.restaurant import Restaurant
And I keep getting `ModuleNotFoundError: No module named 'models'`.
**Note:** both modules (data and models) are int the root folder of the project. And I also tried to make the root folder a module by adding `__init__.py` in it.
[1]: https://i.stack.imgur.com/VCLCV.png
</details>
# 答案1
**得分**: 0
已解决:通过导出 `PYTHONPATH` 环境变量来解决了这个问题:
```sh
export PYTHONPATH=$(pwd)
注意:此解决方案适用于Linux/Mac。
英文:
SOLVED: I solved the problem by exporting PYTHONPATH
environment variable:
export PYTHONPATH=$(pwd)
Note: The solution works on Linux/Mac.
答案2
得分: 0
尝试导入位于不同目录中的同一目录内的内容,请尝试使用:
from ..models.restaurant import Restaurant
以使代码更具可移植性。
英文:
You are trying to import something within the same directory that is in a different directory try using:
from ..models.restaurant import Restaurant
to make the code more portable
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论