Python 相对导入导致 SyntaxError 异常 [英] Python relative import causes SyntaxError exception
问题描述
根据 python 文档,相对导入和包内从 python 2.5 开始支持引用.我目前正在运行 Python 2.7.3.因此,我尝试在我自己的包中实现它,以便将其用于更简单的导入.我很惊讶地发现它向我抛出了一个 SyntaxError 异常,我希望有人能帮助找到原因.
According to the python docs, relative importing and intrapackage referencing has been supported since python 2.5. I am currently running Python 2.7.3. So, I tried to implement this in my own package in order to use it for simpler importing. I was surprised to find it threw a SyntaxError exception at me, and I was hoping someone could help lead the way to the cause.
我设置了一个测试目录进行测试:
I setup a test directory for testing:
tester
├── __init__.py
├── first_level.py
└── sub
├── __init__.py
└── second_level.py
两个 __init__.py 模块都是空的.其他模块是:
Both __init__.py modules are empty. The other modules are:
# first_level.py
print "This is the first level of the package"
<小时>
# sub/second_level.py
import ..first_level
print "This is the second level"
<小时>
当我尝试导入 second_level 模块时,出现以下错误:
When I attempt to import the second_level module, I get the following error:
Python 2.7.3 (default, Aug 1 2012, 14:42:42)
[GCC 4.2.1 Compatible Apple Clang 4.0 ((tags/Apple/clang-421.0.57))] on darwin
Type "help", "copyright", "credits" or "license" for more information.
Welcome!
>>> import tester
>>> import tester.sub.second_level
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "tester/sub/second_level.py", line 1
import ..first_level
^
SyntaxError: invalid syntax
我希望这两行一个接一个地打印,但它引发了一个异常.那么,我做的导入错了吗?你还有其它的想法吗.
I expected the two lines to print one after the other, but it raises an exception instead. So, am I doing the import wrong? Do you have any other ideas.
推荐答案
你不能像那样导入模块.import ..blah
不是有效的导入语法.你需要做 from .. import first_level
.
You can't import modules like that. import ..blah
is not valid import syntax. You need to do from .. import first_level
.
这篇关于Python 相对导入导致 SyntaxError 异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!