Import a zipfile with py file

Question

This snippet creates a zip file with a ‘.py’ inside it. Demonstrates python ability to import a zipfile and run the function inside it.

Solution

import os
import sys
import tempfile
import zipfile

def create_importable_zip(filename):
    z = zipfile.ZipFile(filename, 'w')
    z.writestr('hello.py', 'def f(): return "hello world from " + __file__\n')
    z.close()

def import_and_run_module():
    import hello
    print hello.f()

def main():
    fhandle, filename = tempfile.mkstemp('.zip')

    create_importable_zip(filename)
    sys.path.insert(0, filename)
    import_and_run_module()

    os.close(fhandle)
    os.unlink(filename)


if __name__ == '__main__':
    main()
Run this

Explanation

Running this will emit an output.

hello world from /var/folders/_2/kqmfvpxj3_l3dnj5wq1y6j1c0000gn/T/tmpK1ePKl.zip/hello.py

Note that I have imported import hello using a module name as the name of the zipfile and accessed a function inside it. This demonstrates only ability to package python files and run it as a package.

Comments by Disqus