2012-05-29 119 views
1

我知道很多关于包内导入的问题。我想知道下面的内容是否也适用于Python 2.7。导入Python 2.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

import parserTools.logParser 
import anomalyCheck.DLthput 
import utilities.plotLogResults 
import configuration.TDDFDDconfiguration 
import anomalyCheck.ULthput 
### Work done after here #### 

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

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

--- --- ULThput.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 

我读过几乎所有可用的文档和圭多的指南封装内进口。另外,我想我拥有一切正确的地方。我在这里错过了什么吗?请指出。提前致谢。 :) :)

编辑1:所提到的问题是由琥珀的答案解决。所以,lteDebugger.py通过导入所有其他模块正常工作。现在,另一个问题是,我无法解决的是,当我想编译/解释(无论你想调用)DLThput.py/ULthput.py,它显示与上述相同的错误。 。ValueError:试图超出顶层包的相对导入。我有任何解决方案,其他添加路径到sys黑客?我真的不想这么做,除非这是唯一要做的事情。 那么,我该如何躲避?

+0

in“from ..utilities.plotLogResults import *”为什么你放回“..”?我想你仍然可以导入“从utilities.plotLogResults导入*” –

+0

不,我不认为我可以。虽然会检查。 – VoodooChild92

回答

2

您正在运行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

+0

感谢您的早期答复。因此,您要告诉将lteDebugger.py所在目录的路径添加到sys。对?让我试试它。 – VoodooChild92

+1

这是一种选择,但如果你这样做,你不想使用相对路径 - 你想要使用绝对路径。如果你想继续使用相对路径,你想使用我编辑的方法到我的答案中。 – Amber

+1

Yey!有效。真棒,朋友。 – VoodooChild92