Python relative import causes SyntaxError exceptio

2020-02-01 03:01发布

问题:

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