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):
/home/someone/mypackage/ __init__.py template.html foobar.py
foobar.py script contains this code:
def foo(): 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
The problem is that if your script does the following:
import sys 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:
def package_home(gdict): 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!