Create self contained python executables

Every one knows the special file __init__.py. There is another special file __main__.py. If this file exists in a directory, the python interpreter will try to execute it.

Here is an example of a structure directory with a __main__.py file:

#fred$ find .
./hello
./hello/__main__.py

In our example the content of the file is a simple loop that prints hello world.

#fred$ cat ./hello/__main__.py
for count in range(3):
  print 'hello (cruel) world'

Just call python with the directory name and the python interpreter will execute the file __main__.py

#fred$ python hello
hello (cruel) world
hello (cruel) world
hello (cruel) world

So far nothing speical, but now comes the interesting part...

Python is capable of importing and executing whatever python code is in a zip file. Therefore we can do the following:

#fred$ (cd hello; zip -r ../hello.zip .)
adding: __main__.py (stored 0%)

#fred:$ python hello.zip
hello (cruel) world
hello (cruel) world
hello (cruel) world

On any Unix like system we can use a shebang (#!) line at the beginning of a file to pass the content of that file to the interpreter specified after the shebang.

#fred$ echo '#!/usr/bin/env python' > greetings
#fred$ cat hello.zip >> greetings
#fred$ chmod a+x greetings

This zipped file can now be executed.

#fred$ ./greetings
hello (cruel) world
hello (cruel) world
hello (cruel) world

Mix that with virtualenv and you will have a powerful way to simply distribute and execute your code.

This trick was originaly posted on quora under "What are some cool Python tricks?"


Comments !