I have a folder for my client code, a folder for my server code, and a folder for code that is shared between them
Proj/
Client/
Client.py
Server/
Server.py
Common/
__init__.py
Common.py
How do I import Common.py from Server.py and Client.py?
This question is related to
python
python-3.x
import
shared-libraries
relative-path
The default import method is already "relative", from the PYTHONPATH. The PYTHONPATH is by default, to some system libraries along with the folder of the original source file. If you run with -m to run a module, the current directory gets added to the PYTHONPATH. So if the entry point of your program is inside of Proj, then using import Common.Common
should work inside both Server.py and Client.py.
Don't do a relative import. It won't work how you want it to.
Approch used by me is similar to Gary Beardsley mentioned above with small change.
Filename: Server.py
import os, sys
script_path = os.path.realpath(os.path.dirname(__name__))
os.chdir(script_path)
sys.path.append("..")
# above mentioned steps will make 1 level up module available for import
# here Client, Server and Common all 3 can be imported.
# below mentioned import will be relative to root project
from Common import Common
from Client import Client
Don't do relative import.
From PEP8:
Relative imports for intra-package imports are highly discouraged.
Put all your code into one super package (i.e. "myapp") and use subpackages for client, server and common code.
Update: "Python 2.6 and 3.x supports proper relative imports (...)". See Dave's answers for more details.
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/Client
2. ln -s ../Common ./
3. cd Proj/Server
4. 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.py
from 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 !
Doing a relative import is absolulutely OK! Here's what little 'ol me does:
#first change the cwd to the script path
scriptPath = os.path.realpath(os.path.dirname(sys.argv[0]))
os.chdir(scriptPath)
#append the relative location you want to import from
sys.path.append("../common")
#import your module stored in '../common'
import common.py
Source: Stackoverflow.com