我的项目中的导入有问题。
我的目录结构如下:
base_directory
- examples
- src
- folder_1
- __init__.py
- file.py
- folder_2
- __init__.py
- class1.py
- class2.py
- class3.py
- class4.py
在 file.py
我正在尝试:from ..folder2.class1 import Class1
然后,我收到错误:ImportError: attempted relative import with no known parent package
在
folder2/__init__.py
我做了我在 Python 中制作包的教程中看到的内容:from class1 import Class1
my_class_1 = Class1()
到目前为止,一切都奏效了。我该怎么办?我使用 Python 3.7.5谢谢。
最佳答案
在您的示例中,folder_1 和 folder_2 是两个独立且唯一的包。它们之间没有相对进口。将它们放在一个外包装中以使其工作
base_directory
- examples
- src
- mypackage
- __init__.py
- folder_1
- __init__.py
- file.py
print("imported", __file__)
from ..folder_2.class1 import Class1
print("file.py found", Class1)
- folder_2
- __init__.py
- class1.py
print("imported", __file__)
class Class1:
def __init__(self):
print("Created Class1 instance")
- class2.py
- class3.py
- class4.py
- test.py
import myproject.folder_1.file
运行 test.py 脚本~/tmp/base_directory/src$ python test.py
imported /home/td/tmp/base_directory/src/myproject/folder_1/file.py
imported /home/td/tmp/base_directory/src/myproject/folder_2/class1.py
file.py found <class 'myproject.folder_2.class1.Class1'>
但是有一种解决方法,可以使用“-m”选项调用模块。但他只有在 myproject
时才有效在python路径中。它在这里工作是因为当我调用它时我在 myproject 的父级中。~/tmp/base_directory/src$ python -m myproject.folder_1.file
imported /home/td/tmp/base_directory/src/myproject/folder_1/file.py
imported /home/td/tmp/base_directory/src/myproject/folder_2/class1.py
file.py found <class 'myproject.folder_2.class1.Class1'>
关于Python - 导入错误 : attempted relative import with no known parent package,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62540364/