Running Python Application from Zip File

In the last few days I wrote a python application. It contains some GUI code using pygtk, some communication code, and some files containing register definitions. All in all it’s about 20 files.

Since most users will use it on windows it would be nice to have an executable or a package containing all code. I tried py2exe, but the resulting executable didn’t work. So I was searching for a different solution.

The solution should be:

  • Easy to distribute (one or two files).
  • Easy to create.
  • Work everywhere.

Here is the solution I found:

  • Create a zip file containing all the python code.
  • Create a small python file containing the startup code.
  • In the startup code just add the zip file to sys.path.

OK, so let’s write a little test application:

First create the file appcode.py containing the application code:

def main():
  print "running code from zip file"

Then create a small script createzip.py creating the zip file:
#!/usr/bin/env python

import zipfile

if __name__=='__main__':
  zf = zipfile.ZipFile( "zipappcode.zip", "w" )
  zf.write( "appcode.py", "zipappcode.py" )
  zf.close()

This script stores appcode.py under a different name in the zip file to make sure that the startup code doesn’t just open the original file. Normally I wouldn’t do that, this is just to show that it really loads the code from the zip file.

Now the interesting part, the startup code in zipapp.py:
#!/usr/bin/env python

import os.path
import sys

sys.path.append( os.path.join( os.path.dirname( os.path.abspath( sys.argv[0] ) ), "zipappcode.zip" ) )

import zipappcode

if __name__=='__main__':
  zipappcode.main()

The code isn’t too difficult: First import the modules sys and os.path.

Then add the zip file to sys.path. All the os.path.* stuff is to create the absolute path to the zip file. Without that it would only work when the zip file is in the current working directory.

Now it’s possible to import the application code and run it.

I think this kind of package is really easy to create and use. On windows you can double-click the python file and it just works.

Another nice feature is that the extension of the python file can be changed to .pyw to prevent python from open a console window. This is not useful for this demo app, but for gtk applications it’s really nice.

The only disadvantage is that python and pygtk have to be installed on the machine before eunning the application. But I can live with that.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>