导入文件,导入另一个文件

时间:2019-10-15 06:26:53

标签: python python-3.x import

我想导入一个文件,该文件也可以导入另一个文件。

我目前具有以下目录结构:

.
├── main.py
└── foo
    ├── file1.py
    ├── file2.py
    └── file3.py

使用以下代码:

# main.py
from foo.file1 import func1

func1()


# foo/file1.py
from file2 import func2
from file3 import func3

def func1():
   # Do stuff
   func2()
   func3()

if __name__ == "__main__":
   # Do some other stuff
   func1()


# foo/file2.py
from file3 import func3

def func2():
   # Do stuff
   func3()


# foo/file3.py
def func3():
   # Do stuff

如果我运行main.py,我将得到ModuleNotFoundError: No module named 'file2'

我可以将from file2 import func2中的foo/file1.py行替换为from foo.file2 import func2,并对file3导入执行相同的操作,但是我不能独自运行foo/file1.py

解决此问题的推荐方法是什么?

1 个答案:

答案 0 :(得分:1)

Python3不支持Implicit Relative Imports,例如from file2 import func2,我们需要使用Explicit Relative Imports,例如from .file2 import func2


foo/file1.py中进行更改:

from file2 import func2
from file3 import func3

收件人:

from .file2 import func2
from .file3 import func3

然后在foo/file2.py中进行更改:

from file3 import func3

收件人:

from .file3 import func3

您可能需要阅读:Absolute vs Relative Imports in Python