ModuleNotFoundError with my own modules

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

python3 ModuleNotFoundError with my own modules

问题

  1. ![结构][1]
  2. 我有这个项目的结构。我想在`data/datadownload.py`中像这样导入我的Restaurant类,从`models/restaurant.py`
  3. ```python
  4. from models.restaurant import Restaurant

但我一直得到ModuleNotFoundError: No module named 'models'

注意: data和models两个模块都在项目的根目录中。我还尝试通过在根目录中添加__init__.py来使根目录成为一个模块。

  1. <details>
  2. <summary>英文:</summary>
  3. [![structure][1]][1]
  4. 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

  1. And I keep getting `ModuleNotFoundError: No module named &#39;models&#39;`.
  2. **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.
  3. [1]: https://i.stack.imgur.com/VCLCV.png
  4. </details>
  5. # 答案1
  6. **得分**: 0
  7. 已解决:通过导出 `PYTHONPATH` 环境变量来解决了这个问题:
  8. ```sh
  9. export PYTHONPATH=$(pwd)

注意:此解决方案适用于Linux/Mac。

英文:

SOLVED: I solved the problem by exporting PYTHONPATHenvironment variable:

  1. export PYTHONPATH=$(pwd)

Note: The solution works on Linux/Mac.

答案2

得分: 0

尝试导入位于不同目录中的同一目录内的内容,请尝试使用:

  1. from ..models.restaurant import Restaurant

以使代码更具可移植性。

英文:

You are trying to import something within the same directory that is in a different directory try using:

  1. 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:

确定