Friday, August 14, 2015

Python Executable Zipfiles

Trick source

From the site:
"A new feature that was quietly sneaked into Python 2.6, without the fanfare it deserves, is the ability to distribute Python applications as executable zipfiles. Python has long had support for importing modules and packages from zipfiles - through the oh-so-badly-needed-in-IronPython [1] zipimport. What is new is the ability to make zip archives executable. If you call the Python 2.6+ (or 3.0+) interpreter passing in a zip file instead of a Python file - the interpreter looks inside the zip file for a Python file named __main__.py (at the top-level) and executes it. The zip file can also contain all the (pure-Python only) modules and packages your app depends on. This is a great way of distributing applications as a single file. The nice thing is that the Python interpreter doesn't depend on the extension to recognise zipfiles, instead recognising them automagically. This means that on Windoze you can give these archives a new extension (perhaps '.pyz') and associate them with Python 2.6 - allowing Windows to execute them automatically when you double click on them in explorer. I think, but am not 100% certain, that the zipfile specification is flexible enough that you could also prepend a pound-bang ('#!') interpreter line to make them executable under Mac OS X and Lunix type platforms."

michael$ echo > __main__.py "print 'Hello world'"
michael$ python __main__.py
Hello world
michael$ zip test.zip __main__.py
  adding: __main__.py (stored 0%)
michael$ python test.zip
Hello world

UPDATE: Floris Bruynooghe notes in the comments that you can add a hash-bang line to a zipfile and make it executable:

$ cat > __main__.py
print('hi there')
^D
$ zip test.zip __main__.py
adding: __main__.py (stored 0%)
$ cat > hashbang.txt
#!/usr/bin/env python3.0
^D
$ cat hashbang.txt test.zip > my_exec
$ chmod +x my_exec
$ ./my_exec
hi there
$

No comments: