python-3.x - python3.x : ModuleNotFoundError when import file from parent directory

标签 python-3.x python-import

我是 Python 新手。这真的让我很困惑!

我的目录结构是这样的:

Project
   | - subpackage1
           |- a.py
   | - subpackage2
           |- b.py
   | - c.py  

当我使用 from subpackage1 import aa.py 导入 b.py 时,我得到一个 ModuleNotFoundError。似乎我无法从父目录导入文件。

一些解决方案建议在每个目录中添加一个空文件__init__.py,但这是行不通的。作为解决方法,我在每个子文件(即 a.pyb.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()

还有,ma​​in.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/

相关文章:

python - Python delete_rows 函数中的 openpyxl 破坏了合并的单元格

python - 字典之间的划分

python - 我可以使用 Python 的 Min 函数返回所有最小元组的列表吗?

python - 导入scapy的最佳方法

python - 将目录添加到 sys.path/PYTHONPATH

python - 有没有办法确保 Decimal('0) 乘以某些东西实际上返回 0?

python - 需要减少基于公式和数字 n 创建数字列表的运行时间

python - 在python中导入模块

python - 无法解析导入 [Module] (PylancereportMissingImports),模块位于同一文件夹/目录中

Python __loader__,它是什么?