【问题标题】:Importing classes from different directory within the same project从同一项目中的不同目录导入类
【发布时间】:2020-02-26 12:41:40
【问题描述】:

我有下一个目录结构:

.
├── models
│   ├── description.py
│   ├── identification.py
│   └── person.py
└── utils
    └── generators
        └── person.py

在导入models 目录中存在的每个文件中的类时,我遇到了下一个错误:

Traceback (most recent call last):
  File "utils/generators/person.py", line 1, in <module>
    from models.person import Person
ModuleNotFoundError: No module named 'models'

这是我的utils/generators/person.py 文件中的代码:

from models.person import Person
from models.identification import Identification
from models.description import Description

如何在我的文件中导入这些类?

【问题讨论】:

  • 你的代码是如何运行的?
  • 来自我的终端:python utils/generators/person.py
  • 您是否安装了models 模块?你设置PYTHONPATH了吗?
  • 你可以尝试添加当前文件夹“。”到你的 Python 路径?例如从你的终端运行这个PYTHONPATH=$PYTHONPATH:"." python utils/generators/person.py
  • pythonpath 解决方案对我不起作用

标签: python python-3.x python-import importerror


【解决方案1】:

Python 不会在上级目录的后代目录中搜索导入模块。

要消除此问题,您可以在根目录中引入 main.py(您将其标记为点),它将导入到公共命名空间中。

另外,正如 cmets 中明智地指出的那样,不再需要为 Python 3.3+ 添加空的 __init__.py 文件 (see this answer),因此这不是 Python 3 的问题。

【讨论】:

  • 这不是python2的东西吗?我正在使用 python3
  • 虽然推荐使用 __init__.py 文件,但 Python3 会将没有文件夹的文件夹视为命名空间包。
  • @EnriqueBermúdez:如果您觉得答案有用,您可以考虑接受吗?
  • 我刚用过这个,也不管用。我遇到了同样的错误!
  • 可惜了!我想知道你的 PYTHONPATH 是什么样的。
猜你喜欢
  • 2020-02-13
  • 1970-01-01
  • 2012-09-07
  • 1970-01-01
  • 1970-01-01
  • 2014-10-04
  • 2018-10-12
  • 2020-04-29
  • 1970-01-01
相关资源
最近更新 更多