简体   繁体   English

如何使用这个简单的包避免“在没有已知父包的情况下尝试相对导入”?

[英]How to avoid "Attempted relative import with no known parent package" with this simple package?

Inside packagetest/ , I have these four files:packagetest/ ,我有这四个文件:

  • __init__.py : __init__.py

     class TestError(Exception): pass
  • __main__.py : __main__.py :

     from . import TestError from .abc import defgh from .ijk.lmn import opq
  • abc/__init__.py : abc/__init__.py :

     def defgh(): pass
  • ijk/lmn.py : ijk/lmn.py :

     def opq(): pass

When running __main__.py , I get this error:运行__main__.py ,出现此错误:

File "D:\\packagetest_ main _.py", line 1, in文件“D:\\packagetest_ main _.py”,第 1 行,在
from .从 。 import TestError导入测试错误
ImportError: attempted relative import with no known parent package导入错误:尝试在没有已知父包的情况下进行相对导入

Why does from . import TestError为什么from . import TestError from . import TestError generate an error here? from . import TestError在这里生成错误?

How to solve this problem here and modify the code as little as possible?这里怎么解决这个问题,尽量少修改代码?

I've already read Relative imports in Python 3 but I don't see how to modify my code here to make it work.我已经阅读了 Python 3 中的相对导入,但我不知道如何在此处修改我的代码以使其工作。

The article ImportError: attempted relative import with no known parent package provides several solutions to this problem and explain how relative import works.文章导入错误:尝试在没有已知父包的情况下进行相对导入提供了解决此问题的几种方法,并解释了相对导入的工作原理。

One solution that works for me is to move everything in a parent directory parent/ :对我有用的一种解决方案是将所有内容移动到父目录parent/

parent/
  |- test.py
  |- packagetest/
       |- __init__.py
       |- __main__.py
       |- abc/
           |- __init__.py
       |- ijk/
           |- lmn.py

Then import the package inside parent/test.py :然后在parent/test.py导入包:

import packagetest

and then it works.然后它起作用了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM