首页 > 解决方案 > Python 3 中的导入错误

问题描述

我有 Python 3 中的结构:

my_module/
    my_module/
        any_name.py
    tests/
        tests.py

然后,我尝试在tests.py中使用:

from my_module.any_name import my_class

我收到错误:

ModuleNotFoundError: No module named 'my_module'

有谁知道是什么问题?

标签: pythonpython-3.x

解决方案


my_module首先,拥有and非常令人困惑my_module/my_module,但让我们忽略它。

为了my_module工作,外部my_module必须在你的sys.path.

所以,如果你这样做:

$ cd tests
$ python tests.py

......那么你的sys.path意志只是按照你通常的方式,加上my_module/tests。它不会包含my_module,因此您在任何地方都找不到my_module/my_module

解决方法包括:

  • 有一个顶级test.pyfrom tests import tests.pytests.run()
  • python -m tests.tests从顶级目录运行代码my_module,而不是python tests.pymy_module/tests.
  • 手动tests/tests.py插入os.path.join(__path__, '../my_modulesys.path
  • 使用setuptools/pkg_resources而不是尝试手动执行所有操作。
  • 做这里描述的 hacky 旧式的事情。(你真的不想这样做,除非你需要兼容 Python 2.7 或 3.2 或旧的distribute/distutils版本pkg_resources。)

推荐阅读