EDIT: Fixed ZipImporter to work in everything (I think)
Test data:
mkdir mypkg vim mypkg/__init__.py vim mypkg/test_submodule.py
__init__.py Contents:
def test(): print("Test")
test_submodule.py Contents:
def test_submodule_func(): print("This is a function")
Create a test zip code (on Mac):
zip -r mypkg.zip mypkg rm -r mypkg
Special zip import in inmem_zip_importer.py :
import os import imp import zipfile class ZipImporter(object): def __init__(self, zip_file): self.z = zip_file self.zfile = zipfile.ZipFile(self.z) self._paths = [x.filename for x in self.zfile.filelist] def _mod_to_paths(self, fullname):
Using:
In [1]: from inmem_zip_importer import ZipImporter In [2]: sys.meta_path.append(ZipImporter(open("mypkg.zip", "rb"))) In [3]: from mypkg import test In [4]: test() Test function In [5]: from mypkg.test_submodule import test_submodule_func In [6]: test_submodule_func() This is a function
(from efel) one more thing ...:
To read directly from memory, you will need to do this:
f = open("mypkg.zip", "rb")
source share