Python - 导入错误 : attempted relative import with no known parent package

标签 python python-3.x package python-import importerror

我的项目中的导入有问题。
我的目录结构如下:

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/

相关文章:

python - 在 XML 标签/文本中使用特殊字符

python - scipy.optimize.fmin_slsqp 的使用

python - 有没有办法查看 TfidfVectorizer 输出的 'grams' 列?

Python:使用多处理池从外部函数更新小部件

python - 带有python的谷歌驱动器文件夹中的文件列表

perl - 如何调用在另一个包中声明的子例程而不在子例程名称前加上它的包名?

r - 覆盖另一个包继承的包函数

python - 使用 Python 设置 cx_Oracle 环境变量

python - 编译Python代码时出现unindent does not match any external indenting level错误

python - 跨包模块设置日志记录的有效方法