Python ValueError:尝试在非包中进行相对导入而不是测试包

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37193670/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 19:01:26  来源:igfitidea点击:

ValueError: Attempted relative import in non-package not for tests package

python

提问by codec

I know this has been asked many times but somehow I am not able to get over this error. Here is my directory structure-

我知道这已经被问过很多次了,但不知何故我无法克服这个错误。这是我的目录结构-

project/
  pkg/
  __init__.py
  subpackage1/
        script1.py
        __init__.py
  subpackage2/
        script2.py
       __init__.py

script2.py has:

script2.py 有:

class myclass:
    def myfunction:

script1.py has

script1.py 有

 from ..subpackage2 import script2   

I also tried

我也试过

from ..subpackage2 import myclass

And this gives me : ValueError: Attempted relative import in non-package

这给了我: ValueError: Attempted relative import in non-package

Any help would be really appreciated.

任何帮助将非常感激。

回答by wholevinski

This answer explains what's going on: https://stackoverflow.com/a/73149/769971

这个答案解释了发生了什么:https: //stackoverflow.com/a/73149/769971

You're probably running script1.py from inside the subpackage1/ directory. Change your import to be from subpackage2 import script2, back up to the pkg/ directory, then run python -m subpackage1.script1.

您可能正在 subpackage1/ 目录中运行 script1.py。将您的导入更改为from subpackage2 import script2,备份到 pkg/ 目录,然后运行python -m subpackage1.script1.