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):

 /home/someone/mypackage/
    __init__.py
    template.html
    foobar.py

The 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 package_home.

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!



Comment

Show all 3 comments
 
Name:
Email:
hide my email address.

Your email address will be encoded to prevent email-extraction spiders from reading it so you won't get spammed if you decide to show your email address.