Python relative import causes SyntaxError exception

天大地大妈咪最大 提交于 2019-11-30 07:35:52

问题


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

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"

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.


回答1:


You can't import modules like that. import ..blah is not valid import syntax. You need to do from .. import first_level.




回答2:


I usually do something like:

import sys 
sys.path.append("/home/me/tester")
import first_level 

hope this helps. ~Ben



来源:https://stackoverflow.com/questions/12398442/python-relative-import-causes-syntaxerror-exception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!