Python import path issue. Suggestions and ideas?
Ritesh Nadhani
riteshn at gmail.com
Thu Oct 2 20:52:58 EDT 2008
Hello All
So my sourcecode has the following structure:
/
- app.py
- commonlib.py
- app.cnf
- module/
- module/submodule/
- module/submodule/app2.py
Commonlib is generally used for one method:
def GetConfValue(section, item):
config = ConfigParser.ConfigParser()
config.read( "app.cnf" )
return config.get(section, item)
So in app.py, I have:
from commonlib import *
and I can use the method, GetConfValue().
Now, if I want to use the same method in app2.py, so if I do:
from CommonLib import * - it naturally throws up an error.
So as a first reaction, I created another file - app2_dummy.py in the same
folder as app.py, and added the code:
from module.submodule.app2 import main as app2main
app2main()
which as you can see - a very bad way!!!!
Doing a Google search threw up bunch of stuff on os.path.append and looking
at it, I added the following two lines at top of app2.py
sys.path.append("/".join(os.path.abspath(sys.argv[0]).split('/')[:-3]))
looks ugly but adds the path correctly and I can use, import CommonLib.
So my question, is this the correct way of doing things? This means I will
have to put this line in every python script in that folder and subsequent
folder.
Why I ask is that when I was calling GetConfValue() from app2.py, it gave me
error that app.cnf was not found which is probably due to the fact that
app2.py was started from module/submodule/, so I changed the method to:
def GetConfValue(section, item):
config = ConfigParser.ConfigParser()
config.read( os.path.dirname(__file__) + os.sep + "app.cnf" )
return config.get(section, item)
which then works.
I even found that you can tell Python to add folder using .pth but I added
app.pth in module/submodule/ and had the line:
../../
but it didnt work either (I believe I am doing something very stupid on that
part.....)
Thoughts?
Ritesh
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20081002/4d14f4bb/attachment.html>
More information about the Python-list
mailing list