ModuleNotFoundError with my own modules

huangapple go评论63阅读模式
英文:

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 &#39;models&#39;`.

**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 PYTHONPATHenvironment 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

huangapple
  • 本文由 发表于 2023年3月31日 20:40:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/75898648.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定