What is the proper way to access resources in python programs.
Basically in many of my python modules I end up writing code like that:
DIRNAME = os.path.split(__file__)[0]
(...)
template_file = os.path.join(DIRNAME, "template.foo")
Which is OK but:
- It will break if I will start to use python zip packages
- It is boilerplate code
In Java I had a function that did exactly the same --- but worked both when code was lying in bunch of folders and when it was packaged in .jar
file.
Is there such function in Python, or is there any other pattern that I might use.
You'll want to look at using either get_data in the stdlib or pkg_resources from setuptools/distribute. Which one you use probably depends on whether you're already using distribute to package your code as an egg.
I guess the zipimport standard python module could be an answer...
EDIT: well, not the use of the module directly, but using
sys.path
as shown in the example could be a good way:test.zip
with one python moduletest
and a filetest.foo
insidetest
can be aware of oftest.foo
, it contains this code:c
Test looks ok:
So a solution could be to loop in your zip file to retrieve all python modules, and add them in
sys.path
; this piece of code would be ideally the 1st one loaded by your application.Trying to understand how we could combine the two aspect togather
Reading through the quick tutorial on zipimport : http://www.doughellmann.com/PyMOTW/zipimport/
I see the following example:
I think that output of __file__ is "zipimport_example.zip/example_package/__init__.pyc"
Need to check how it looks from inside.
But then we could always do something like this:
[Edit:] I have tried to work out the example a bit better.
If the the package gets imported as zipped file then, two things happen
If these two conditions are met then within the package you could do:
else the module was loaded normally and you can follow the regular approach to loading the file.