Python 2.7错误中的imp

2024-05-15 23:54:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我知道有很多关于包内导入的问题。我想知道下面的方法是否也适用于Python2.7。在

Source/
anomalyCheck/
    __init__.py
    DLthput.py
    ULPowerStats.py
    ULThput.py
config/
    __init__.py
    configure.py
parserTools/
    __init__.py
    logParser.py
utilities/
    __init__.py
    plotLogResults.py
__init__.py
lteDebugger.py

---lteDebugger.py----在

^{pr2}$

在------DLThput.py------在

from ..utilities.plotLogResults import *
from ..parserTools.logParser import *
### Work done after here ####

在------超高强度.py-------在

from ..parserTools.logParser import *
from ..utilities.plotLogResults import *

错误:

在运行lteDebugger.py文件,错误是

ValueError: Attempted relative import beyond toplevel package

File "C:\Users\manojtut\Desktop\Project_LTE_SVN\Source\lteDebugger.py", line 2, in 
  import anomalyChecker.DLthput
File "C:\Users\manojtut\Desktop\Project_LTE_SVN\Source\anomalyChecker\DLthput.py", line 1, in 

我已经阅读了几乎所有可用的文档和Guido的包内导入指南。而且,我想我把所有的东西都放在了正确的地方。我是不是少了点什么?请指出。事先非常感谢。:):)

编辑1:上面提到的问题由安伯的答案解决了。所以,lteDebugger.py通过导入所有其他模块工作正常。现在,另一个问题是,我无法解决的是。。。当我想编译/解释(无论你想调用什么)时DLThput.py/ULthput.py,它显示与上面相同的错误。。。ValueError:尝试在顶级包之外进行相对导入。我有没有其他的解决办法来增加系统黑客的路径?我真的不想那样做,除非这是唯一能做的事。 那么,我怎么才能躲过这个?在


Tags: frompyimportsourceinit错误fileutilities
1条回答
网友
1楼 · 发布于 2024-05-15 23:54:18

您正在运行lteDebugger.py,这意味着任何“包”都必须在目录树中至少低一级-它们需要包含在一个文件夹中,以便Python将它们识别为包而不是模块(从而使相对导入正常工作)。在

anomalyCheck被识别为一个包,但它的父目录不是(因为lteDebugger.py就在那里),因此不允许使用相对导入来转到该父目录。在

解决此问题的一种方法是将lteDebugger.py以外的所有内容移动到子目录中,例如:

Source/
    debugger/
        anomalyCheck/
            __init__.py
            DLthput.py
            ULPowerStats.py
            ULThput.py
        config/
            __init__.py
            configure.py
        parserTools/
            __init__.py
            logParser.py
        utilities/
            __init__.py
            plotLogResults.py
        __init__.py
    lteDebugger.py

然后lteDebugger.py会做类似import debugger.anomalyCheck.DLthput.py的事情。在

相关问题 更多 >