Python 3.5无法导入模块

Python 3.5 cannot import a module

我已经阅读了大量的 Whosebug 答案和大量教程。此外,我尝试阅读 Python 文档,但无法使 import 起作用。

目录如下所示:

myDirectory
    ├── __init__.py
    ├── LICENSE
    ├── project.py
    ├── README.md
    ├── stageManager.py
    └── tests
        ├── __init__.py
        └── test_project.py

project.py里有个class叫Project,我想把它导入到tests目录下的一个文件里。我尝试了以下方法:

相对导入:

from ..project import Project

def print_sth():
    print("something")

这给了我以下错误:(运行ning 从 tests 目录作为 python test_project.py 和从 myDirectory 作为 python tests/test_project.py)

Traceback (most recent call last):
    File "test_project.py", line 1, in <module>
       from ..project import Project
SystemError: Parent module '' not loaded, cannot perform relative import

带包名的绝对导入:

如果我有类似下面的东西,我会得到 ImportError(使用与上面相同的 运行 命令)。

from project import Project

def print_sth():
    print("something")

------------------------------------------------------
Traceback (most recent call last):
    File "test_project.py", line 1, in <module>
        from project import Project
ImportError: No module named 'project'

还有这个:

from myDirectory.project import Project

def print_sth():
    print("something")

------------------------------------------------------
Traceback (most recent call last):
    File "test_project.py", line 1, in <module>
       from myDirectory.project import Project 
ImportError: No module named 'myDirectory'

最后,我尝试在 test_project.py 文件中添加 if __name__ == '__main__' 语句,但仍然失败。如果有人能提供帮助,我将不胜感激。如果有一个我不必编写冗长命令的解决方案,我会更喜欢。

当你按文件名 运行 一个 Python 脚本时,Python 解释器假定它是一个 top-level 模块(并添加脚本所在的目录到模块搜索路径)。如果脚本在包中,那是不正确的。相反,您应该 运行 使用 -m 标志的模块,它采用与导入语句(点分隔符)相同格式的模块名称,并将当前目录放在模块搜索路径中。

因此,您可以 运行 来自 myDirectory 的测试:python -m tests.test_project。当您以这种方式 运行 脚本时,您尝试的任何一种导入都将起作用。

但是如果 myDirectory 应该是一个 top-level 包本身(正如 __init__.py 文件所建议的那样),你应该更上一层楼,到 myDirectory 的父级,以及 运行 具有两级包名称的脚本:python -m myDirectory.tests.test_project。如果您这样做并希望测试使用绝对导入,您需要命名 project 模块所在的顶级包:from myDirectory.project import Project.