Create self contained python executables

Posted by Fred C (W6BSD) on Aug 21 2015

Every one knows the special file There is another special file 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 file:

#fred$ find .

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

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

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

#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 ../ .)
adding: (stored 0%)

#fred:$ python
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 >> 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?"