Importing from a relative path in Python
EDIT Nov 2014 (3 years later):
Python 2.6 and 3.x supports proper relative imports, where you can avoid doing anything hacky. With this method, you know you are getting a relative import rather than an absolute import. The '..' means, go to the directory above me:
from ..Common import Common
As a caveat, this will only work if you run your python as a module, from outside of the package. For example:
python -m Proj
Original hacky way
This method is still commonly used in some situations, where you aren't actually ever 'installing' your package. For example, it's popular with Django users.
You can add Common/ to your sys.path (the list of paths python looks at to import things):
import sys, ossys.path.append(os.path.join(os.path.dirname(__file__), '..', 'Common'))import Common
os.path.dirname(__file__)
just gives you the directory that your current python file is in, and then we navigate to 'Common/' the directory and import 'Common' the module.
Doing a relative import is absolulutely OK! Here's what little 'ol me does:
#first change the cwd to the script pathscriptPath = os.path.realpath(os.path.dirname(sys.argv[0]))os.chdir(scriptPath)#append the relative location you want to import fromsys.path.append("../common")#import your module stored in '../common'import common.py
Funny enough, a same problem I just met, and I get this work in following way:
combining with linux command ln
, we can make thing a lot simper:
1. cd Proj/Client2. ln -s ../Common ./3. cd Proj/Server4. ln -s ../Common ./
And, now if you want to import some_stuff
from file: Proj/Common/Common.py
into your file: Proj/Client/Client.py
, just like this:
# in Proj/Client/Client.pyfrom Common.Common import some_stuff
And, the same applies to Proj/Server
, Also works for setup.py
process,a same question discussed here, hope it helps !