我是 Python 新手。这真的让我很困惑!
我的目录结构是这样的:
Project
| - subpackage1
|- a.py
| - subpackage2
|- b.py
| - c.py
当我使用 from subpackage1 import a
将 a.py
导入 b.py
时,我得到一个 ModuleNotFoundError。似乎我无法从父目录导入文件。
一些解决方案建议在每个目录中添加一个空文件__init__.py
,但这是行不通的。作为解决方法,我在每个子文件(即 a.py
和 b.py
)中放置了以下内容以访问父目录:
import os
import sys
sys.path.append(os.path.abspath('..'))
我试图在子文件中输出sys.path
,它只包括当前文件路径和anaconda路径,所以我必须将..
附加到系统路径
。
我该如何解决这个问题?有没有更有效的方法?
最佳答案
假设我们有这个文件和目录树:
$> tree
.
├── main.py
├── submodule1
│ ├── a.py
│ └── __init__.py
└── submodule2
├── b.py
└── __init__.py
2 directories, 5 files
所以,这里有一个示例,说明如何从 a.py
inti b.py
进行导入,反之亦然。
a.py
try:
# Works when we're at the top lovel and we call main.py
from submodule1 import b
except ImportError:
# If we're not in the top level
# And we're trying to call the file directly
import sys
# add the submodules to $PATH
# sys.path[0] is the current file's path
sys.path.append(sys.path[0] + '/..')
from submodule2 import b
def hello_from_a():
print('hello from a')
if __name__ == '__main__':
hello_from_a()
b.hello_from_b()
b.py
try:
from submodule1 import a
except ImportError:
import sys
sys.path.append(sys.path[0] + '/..')
from submodule1 import a
def hello_from_b():
print("hello from b")
if __name__ == '__main__':
hello_from_b()
a.hello_from_a()
还有,main.py:
from submodule1 import a
from submodule2 import b
def main():
print('hello from main')
a.hello_from_a()
b.hello_from_b()
if __name__ == '__main__':
main()
演示:
当我们在顶层并且我们试图调用 main.py
$> pwd
/home/user/modules
$> python3 main.py
hello from main
hello from a
hello from b
当我们在/modules/submodule1 级别并且我们试图调用 a.py
$> pwd
/home/user/modules/submodule1
$> python3 a.py
hello from a
hello from b
当我们是/modules/submodule2 级别并且我们试图调用 b.py
$> pwd
/home/user/modules/submodule2
$> python3 b.py
hello from b
hello from a
关于python-3.x - python3.x : ModuleNotFoundError when import file from parent directory,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54339118/