Sunday, December 12, 2010

running directories and zip files in python

After coding an application in python,I wanted to distribute the source in a way any user can run the application without bothering to install it.Luckily ,in Python 2.6 ,a zip archive or directory can be executed by passing their names to python interpreter.
The section http://docs.python.org/release/2.6.5/whatsnew/2.6.html#other-language-changes mentions.
"Directories and zip archives containing a __main__.py file can now be executed directly by passing their name to the interpreter.The directory or zip archive is automatically inserted as the first entry in sys.path."

Suppose my application contains a package called 'mypackage' which has all the application code.I can create a front-end to the application and put it in a file called __main__.py

import mypackage
mypackage.myapplication_method()

1.executing the directory
I put this __main__.py file and mypackage into a folder mycode.Now the folder structure is say,

C:\python\mycode
-- mypackage
-- __main__.py

Now ,at the command prompt ,I can cd to C:\python and call python mycode to execute the application.

2.executing the zip archive
Put the __main__.py and mypackage in to a zip file ,say myzip.zip.Copy this zipfile to C:\python directory.At the command prompt ,cd to C:\python and run python myzip.zip to execute the application.

There is no need to set PYTHONPATH.
These two facilities make life easier for those who doesn't want to go to the trouble of creating/running setup scripts just to distribute/execute a demo application which may contain multiple packages.

No comments:

Post a Comment