Last Updated: February 20, 2018
·
2.476K
· rkulla

Execute any file as a python application

As of Python 2.6 you can execute ZIP files or directories as python programs - as long as they contain a top-level __main__.py file. And because Python uses magic file detection to determine if the file is a zip archive, you don't even have to use a .zip extension. Furthermore, if you prepend a Shebang path to the python interpreter to the zip archive, you can execute it as a standalone. Let's see an example.

$ cd /tmp
$ mkdir tryit
$ cd tryit

# Create a python file called hi.py that prints "hello"
$ echo 'print "hello"' > hi.py

# Create __main__.py as the main entry point of the app
$ echo 'import hi' > __main__.py

# Zip it, ensuring that __main__.py is at very top-level
$ zip -r foo.zip .

# Prepend python binary and ditch the .zip file extension
$ echo '#!/usr/bin/env python' | cat - foo.zip > foo

# Make the file executable
$ chmod +x foo

# See what file type it shows as on Linux
$ file foo
data (although on my mac it says: a python script text executable)

Now you can just give someone the file and, as long as they have python installed somewhere, they should be able to run it with just:

$ ./foo
hello

What makes this impressive is that the file could contain a thousand python files and it will still work.