python-3.x - python3.x:从父目录导入文件时出现 ModuleNotFoundError
问题描述
我是 Python 新手。这真的让我很困惑!
我的目录结构是这样的:
Project
| - subpackage1
|- a.py
| - subpackage2
|- b.py
| - c.py
当我导入a.py
withb.py
时from subpackage1 import a
,我得到一个ModuleNotFoundError。好像我无法从父目录导入文件。
一些解决方案建议在每个目录中添加一个空文件__init__.py
,但这不起作用。作为一种解决方法,我在每个子文件(即a.py
和b.py
)中放置了以下内容以访问父目录:
import os
import sys
sys.path.append(os.path.abspath('..'))
我试图sys.path
在子文件中输出,它只包括当前文件路径和anaconda路径,所以我必须追加..
到sys.path
.
我怎么解决这个问题?有没有更有效的方法?
解决方案
假设我们有这个文件和目录树:
$> tree
.
├── main.py
├── submodule1
│ ├── a.py
│ └── __init__.py
└── submodule2
├── b.py
└── __init__.py
2 directories, 5 files
因此,这是一个如何从a.py
inti进行导入的示例,b.py
反之亦然。
一个.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
推荐阅读
- c# - 将列映射到 Dapper 中的数组
- java - IntelliJ Java 配置
- r - foreach 实现崩溃并在 R 中生成错误
- python - 删除所有布尔列都为 False 的行 - Python
- python - np.argamx 不返回整数
- powershell - 使用 PowerShell 从网页按钮单击下载文件
- python - 如何将元组保存到python中的excel
- python - 如何修复 Django 和 Postgres SQL 中布尔类型的无效输入语法:“abc”?
- reactjs - 此表达式不可调用。类型“{}”没有调用签名。TS2349
- api - 如何配置 Krakend 使其按原样返回 http 重定向响应而不是遵循 http 重定向?