Python package path when executed elsewhere
14th of December 2004
I stumbled across a problem today with running a python package from a different directory than where the python files are. The package looked like this (in principle):
__init__.py
template.html
foobar.py
The foobar.py script contains this code:
tmpl = open('template.html').read()
return tmpl.replace('X','Y')
That's fine and works when you run the file directly. The problem comes when you run the foobar.py script from somewhere completely different (e.g. /home/mrbloggs/otherpackage/).
The solution to this comes from Zope's package_home.
The problem is that if your script does the following:
sys.path.insert(0, '/home/someone/mypackage')
import foobar
foobar.foo()
Then the file template.html can not be found. That's because upon executing the importing script it holds a different execution path.
So what I did was that I added the following code which I pinched from Zope's package_home:
filename = gdict["__file__"]
return os.path.dirname(filename)
def foo():
tmpl = open(os.path.join(package_home(globals()), 'template.html')).read()
return tmpl.replace('X','Y')
Good to know for the future!