Importing Python Modules from Zip Archives Using zipimport














































Importing Python Modules from Zip Archives Using zipimport



Importing Python Modules from Zip Archives - zipimport


zipimport provides support for importing Python modules from Zip archives. This module adds the ability to import

Python modules ('.py') and packages from ZIP-format archives. It is usually not needed to use the Zipimport module

explicitly.

This module also allows an item of sys.path to be a string naming a ZIP file archive. The ZIP archive can contain a

subdirectory structure to support package imports and a path within the archive can be specified to only import from.

It is automatically used by the built-in import mechanism for sys.path items that are paths to ZIP archives.

Let us see an example of how the zipimport module works Through an example.


Example:


This example uses some of My previous code and Zipfile Module to create an example ZIP archive containing a

few Python modules.


# createzip.py

#!/usr/bin/env python

# -*- coding: utf-8 -*-

import zipfile

import glob

"""

this python package implements the zipfile class and writes the python

packages into zip archive

"""

class CreateZip:

def __init__(self, pathname):

self.path = pathname


def Create(self, filename):

files = glob.glob(self.path)

zf = zipfile.PyZipFile(filename, mode='w')

print('*'*52)

print('Creating Zip.......')

print('*'*52)

for file in files:

zf.write(file)

for name in zf.namelist():

print(name)

print()

print('Zip Created Successfully...')

zf.close()       # always close the file in the end 


def main():

zip = CreateZip('*.py')      

zip.Create('zipimg.zip')  # name of the your zipfile


if __name__ == '__main__':

main()


Run CreateZip.py file to create a ZIP archive containing all of the modules in your current  directory


Output:




ZIPIMPORTER OBJECTS


The 'zipimport' module defines zipimporter class in which the following methods are defined:

zipimporter(): This method is the constructor which creates a new zipimporter instance. It requires a path to a ZIP file

argument. ZipImportError is raised if it is not a valid ZIP archive.

find_module(): It returns the zipimporter instance if the module was found, or None if it Wasn't.

get_source(): This method returns the source code for the specified module.

load_module()  : This method loads the module specified. It returns the imported module else raises ZipImportError

if not found.

get_code(): This method returns the code object for the specified module else raises ZipImportError if the module

couldn't be found.


Example:


import zipimport


class ZipImporter:

def __init__(self, filepath):

self.path = filepath

self.zip= zipimport.zipimporter(self.path)

def Load(self, Filename):

try:

mod= self.zip.load_module(Filename)

print(f'Imported Module : {mod.__name__}')

except:

print('Module Not found. ')


def Print_Code(self,Filename):

code=self.zip.get_source(Filename)

print(f'Source Code : ')

print(code)

def Get_module(self,name):

module=self.zip.find_module(name)

if module:

print(f"Module object : {module}")

else:

print(f"Module object : Not Found")


def main():

zf=ZipImporter('zipimg.zip')

zf.Get_module('sese')

zf.Load('duplicatedic')

zf.Print_Code('duplicatedic')


if __name__ == "__main__":

main()


Output :







Comments