python relative import example code does not work
Possible Duplicate:
How to properly use relative or absolute imports in Python modules?
我有这个文件布局,如本例所示:(下载地址:http://www.mediafire.com/?oug42nzvxrvoms4)http://www.python.org/dev/pep s/pep-0328/guido-s-decision
modulex包含:
1 2 3 4 5 6 7 8 | from .moduleY import spam from .moduleY import spam as ham from . import moduleY from ..subpackage1 import moduleY from ..subpackage2.moduleZ import eggs from ..moduleA import foo from ...package import bar from ...sys import path |
这就是发生的事情:
1 2 3 4 5 | C:\package\subpackage1>python moduleX.py Traceback (most recent call last): File"moduleX.py", line 1, in <module> from .moduleY import spam ValueError: Attempted relative import in non-package |
我有python 2.7.2。我有
1 | __init__.py |
每个目录中的文件。为什么此代码不起作用?
从文档:
- www.python.org http:/ / / / dev / PEP peps支撑# Guido的决策
你可以看到这个:
Relative imports use a module's name attribute to determine that module's position in the package hierarchy. If the module's name does not contain any package information (e.g. it is set to 'main') then relative imports are resolved as if the module were a top level module, regardless of where the module is actually located on the file system.
1 | python -m package.subpackage1.moduleX |
本想把modulex顶级进口和在包中。运行从顶级法:
1 2 3 4 5 6 7 8 9 10 | package/ __init__.py subpackage1/ __init__.py moduleX.py moduleY.py subpackage2/ __init__.py moduleZ.py moduleA.py |
你可以从
1 | c:\>python -m package.subpackage1.moduleX |
一个音符,是进口
1 2 3 4 5 6 7 8 | from .moduleY import spam from .moduleY import spam as ham from . import moduleY from ..subpackage1 import moduleY from ..subpackage2.moduleZ import eggs from ..moduleA import foo from ...package import bar from ...sys import path |
第二个负载:
1 | from ...package import bar |
需要在根文件夹(在你的
本线:
1 | from ...sys import path |
有一个纸条上面的链接:PEP 328
Note that while that last case is legal, it is certainly discouraged ("insane" was the word Guido used).
所以,关于这个湖的其他soqs可以帮助:
- 如何在Python做相对进口?
- 有人可以解释相对进口Python?
- 如何完成相对进口在Python
- 相对weirdness Python导入
- 在Python中,相对进口
希望这帮助。