How to run python code from a zip archive

Viewed 97

I have a python file inside a zip archive which I want to run directly from a python notebook. Better yet, I'd prefer if I could import from it.

So far I have this:

import zipfile

with zipfile.ZipFile('archive.zip', mode='r') as zf:
    with zf.open('code.py') as f:
        # what now?

I suppose I could save the file somewhere then import from it. Maybe even using tempfile so I can clean up right away (hmm now that I try to implement tempfile, it doesn't feel so straight forward). But just wondering if I don't know what I don't know.

1 Answers

From the documentation on zipimport (https://docs.python.org/3/library/zipimport.html) it looks like you can just reference the file you need to use within the zip like so: -

Examples Here is an example that imports a module from a ZIP archive - note that the zipimport > module is not explicitly used.


$ unzip -l example.zip
Archive:  example.zip
  Length     Date   Time    Name
 --------    ----   ----    ----
     8467  11-26-02 22:30   jwzthreading.py
 --------                   -------
     8467                   1 file
$ ./python
Python 2.3 (#1, Aug 1 2003, 19:54:32)
>>> import sys
>>> sys.path.insert(0, 'example.zip')  # Add .zip file to front of path
>>> import jwzthreading
>>> jwzthreading.__file__
'example.zip/jwzthreading.py'

There's some more complex examples in this article here

https://pymotw.com/2/zipimport/


import zipimport

importer = zipimport.zipimporter('zipimport_example.zip')
code = importer.get_code('zipimport_get_code')
print code

Related