Python import modules from Zip archives (zipimport)


Use of 'zipimport' module makes it possible to import Python modules and packages from ZIP-format archives. This module also allows an item of sys.path to be a string naming a ZIP file archive. Any files may be present in the ZIP archive, but only files .py and .pyc are available for import. ZIP import of dynamic modules is disallowed.

Functionality of this module is explained by first building a zip archive of files in 'newdir' directory. Following files are assumed to be present in newdir directory

['guess.py', 'hello.py', 'impzip.py', 'mytest.py', 'prime.py', 'prog.py', 'tmp.py']

import sys, glob
import zipfile
files = glob.glob("*.py")
print (files)
zf = zipfile.PyZipFile('zipimp.zip', mode='w')
for file in files:
   zf.write(file)
zf.close()

We now use 'zipimp.zip' in rest of the article.

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

zipimporter()

This method is the constructor which creates a new zipimporter instance. It requires path to a ZIP filea s argument. ZipImportError is raised if it is not a valid ZIP archive.

>>> import zipimport
>>> importer = zipimport.zipimporter('zipimp.zip')

find_module()

This method earchs for a module specified. It returns the zipimporter instance if the module was found, or None if it wasn’t.

>>> ret=importer.find_module('prime')
>>> ret
<zipimporter object "zipimp.zip">
>>> ret=importer.find_module('sample')
>>> ret
>>> print (ret)
None

get_code()

This method returns the code object for the specified module, raises ZipImportError if the module couldn’t be found.

>>> prog=importer.get_code('prime')
>>> print (prog)
<code object <module> at 0x022A4650, file "zipimp.zip\prime.py", line 1>

load_module()

This method loads the module specified. It returns the imported module, or raises ZipImportError if it wasn’t found.

>>> importer = zipimport.zipimporter('zipimp.zip')
>>> mod=importer.load_module('prog')
30
>>> mod.__name__
'prog'
>>> mod.__file__
'zipimp.zip\prog.py'
>>> mod.__loader__
<zipimporter object "zipimp.zip">

get_source()

This method returns the source code for the specified module.

>>> prog=importer.get_source('prime')
>>> print (prog)
def isprime(x):
   for i in range(2,x-1):
      if x%i==0:
      return False
   else:
return True
f = int(input())
l = int(input())
primelist = list(filter(isprime, range(f,l)))
print ("prime1", "prime2", "composites")
composites=[(primelist[i-1], primelist[i],(primelist[i]-1)-primelist[i-1]) for i in range(1,len(primelist))]
print (composites)

Updated on: 30-Jul-2019

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements