Python相对导入导致SyntaxError异常 [英] Python relative import causes SyntaxError exception

查看:175
本文介绍了Python相对导入导致SyntaxError异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据 python docs ,相对导入和内包装自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 无效的导入语法。你需要从.. 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆