"""zipimport provides support for importing Python modules from Zip archives.
This module exports three objects:
- zipimporter: a class; its constructor takes a path to a Zip archive.
- ZipImportError: exception raised by zipimporter objects. It's a
subclass of ImportError, so it can be caught as ImportError, too.
- _zip_directory_cache: a dict, mapping archive paths to zip directory
info dicts, as used in zipimporter._files.
It is usually not needed to use the zipimport module explicitly; it is
used by the builtin import mechanism for sys.path items that are paths
#from importlib import _bootstrap_external
#from importlib import _bootstrap # for _verbose_message
import _frozen_importlib_external as _bootstrap_external
from _frozen_importlib_external import _unpack_uint16, _unpack_uint32
import _frozen_importlib as _bootstrap # for _verbose_message
import _imp # for check_hash_based_pycs
import marshal # for loads
__all__ = ['ZipImportError', 'zipimporter']
path_sep = _bootstrap_external.path_sep
alt_path_sep = _bootstrap_external.path_separators[1:]
class ZipImportError(ImportError):
# _read_directory() cache
_zip_directory_cache = {}
END_CENTRAL_DIR_SIZE = 22
STRING_END_ARCHIVE = b'PK\x05\x06'
MAX_COMMENT_LEN = (1 << 16) - 1
"""zipimporter(archivepath) -> zipimporter object
Create a new zipimporter instance. 'archivepath' must be a path to
a zipfile, or to a specific path inside a zipfile. For example, it can be
'/tmp/myimport.zip', or '/tmp/myimport.zip/mydirectory', if mydirectory is a
valid directory inside the archive.
'ZipImportError is raised if 'archivepath' doesn't point to a valid Zip
The 'archive' attribute of zipimporter objects contains the name of the
# Split the "subdirectory" from the Zip archive path, lookup a matching
# entry in sys.path_importer_cache, fetch the file directory from there
# if found, or else read it from the archive.
def __init__(self, path):
if not isinstance(path, str):
raise ZipImportError('archive path is empty', path=path)
path = path.replace(alt_path_sep, path_sep)
st = _bootstrap_external._path_stat(path)
except (OSError, ValueError):
# On Windows a ValueError is raised for too long paths.
# Back up one path element.
dirname, basename = _bootstrap_external._path_split(path)
raise ZipImportError('not a Zip file', path=path)
if (st.st_mode & 0o170000) != 0o100000: # stat.S_ISREG
raise ZipImportError('not a Zip file', path=path)
files = _zip_directory_cache[path]
files = _read_directory(path)
_zip_directory_cache[path] = files
# a prefix directory following the ZIP file path.
self.prefix = _bootstrap_external._path_join(*prefix[::-1])
# Check whether we can satisfy the import of the module named by
# 'fullname', or whether it could be a portion of a namespace
# package. Return self if we can load it, a string containing the
# full path if it's a possible namespace portion, None if we
def find_loader(self, fullname, path=None):
"""find_loader(fullname, path=None) -> self, str or None.
Search for a module specified by 'fullname'. 'fullname' must be the
fully qualified (dotted) module name. It returns the zipimporter
instance itself if the module was found, a string containing the
full path name if it's possibly a portion of a namespace package,
or None otherwise. The optional 'path' argument is ignored -- it's
there for compatibility with the importer protocol.
mi = _get_module_info(self, fullname)
# This is a module or package.
# Not a module or regular package. See if this is a directory, and
# therefore possibly a portion of a namespace package.
# We're only interested in the last path component of fullname
# earlier components are recorded in self.prefix.
modpath = _get_module_path(self, fullname)
if _is_dir(self, modpath):
# This is possibly a portion of a namespace
# package. Return the string representing its path,
# without a trailing separator.
return None, [f'{self.archive}{path_sep}{modpath}']
# Check whether we can satisfy the import of the module named by
# 'fullname'. Return self if we can, None if we can't.
def find_module(self, fullname, path=None):
"""find_module(fullname, path=None) -> self or None.
Search for a module specified by 'fullname'. 'fullname' must be the
fully qualified (dotted) module name. It returns the zipimporter
instance itself if the module was found, or None if it wasn't.
The optional 'path' argument is ignored -- it's there for compatibility
with the importer protocol.
return self.find_loader(fullname, path)[0]
def get_code(self, fullname):
"""get_code(fullname) -> code object.
Return the code object for the specified module. Raise ZipImportError
if the module couldn't be found.
code, ispackage, modpath = _get_module_code(self, fullname)
def get_data(self, pathname):
"""get_data(pathname) -> string with file data.
Return the data associated with 'pathname'. Raise OSError if
pathname = pathname.replace(alt_path_sep, path_sep)
if pathname.startswith(self.archive + path_sep):
key = pathname[len(self.archive + path_sep):]
toc_entry = self._files[key]
raise OSError(0, '', key)
return _get_data(self.archive, toc_entry)
# Return a string matching __file__ for the named module
def get_filename(self, fullname):
"""get_filename(fullname) -> filename string.
Return the filename for the specified module.
# Deciding the filename requires working out where the code
# would come from if the module was actually loaded
code, ispackage, modpath = _get_module_code(self, fullname)
def get_source(self, fullname):
"""get_source(fullname) -> source string.
Return the source code for the specified module. Raise ZipImportError
if the module couldn't be found, return None if the archive does
contain the module, but has no source for it.
mi = _get_module_info(self, fullname)
raise ZipImportError(f"can't find module {fullname!r}", name=fullname)
path = _get_module_path(self, fullname)
fullpath = _bootstrap_external._path_join(path, '__init__.py')
toc_entry = self._files[fullpath]
# we have the module, but no source
return _get_data(self.archive, toc_entry).decode()
# Return a bool signifying whether the module is a package or not.
def is_package(self, fullname):
"""is_package(fullname) -> bool.
Return True if the module specified by fullname is a package.
Raise ZipImportError if the module couldn't be found.
mi = _get_module_info(self, fullname)
raise ZipImportError(f"can't find module {fullname!r}", name=fullname)
# Load and return the module named by 'fullname'.
def load_module(self, fullname):
"""load_module(fullname) -> module.
Load the module specified by 'fullname'. 'fullname' must be the
fully qualified (dotted) module name. It returns the imported
module, or raises ZipImportError if it wasn't found.
code, ispackage, modpath = _get_module_code(self, fullname)
mod = sys.modules.get(fullname)
if mod is None or not isinstance(mod, _module_type):
mod = _module_type(fullname)
sys.modules[fullname] = mod
# add __path__ to the module *before* the code gets
path = _get_module_path(self, fullname)
fullpath = _bootstrap_external._path_join(self.archive, path)
mod.__path__ = [fullpath]
if not hasattr(mod, '__builtins__'):
mod.__builtins__ = __builtins__
_bootstrap_external._fix_up_module(mod.__dict__, fullname, modpath)
del sys.modules[fullname]
mod = sys.modules[fullname]
raise ImportError(f'Loaded module {fullname!r} not found in sys.modules')
_bootstrap._verbose_message('import {} # loaded from Zip {}', fullname, modpath)
def get_resource_reader(self, fullname):
"""Return the ResourceReader for a package in a zip file.
If 'fullname' is a package within the zip file, return the
'ResourceReader' object for the package. Otherwise return None.
if not self.is_package(fullname):
if not _ZipImportResourceReader._registered:
from importlib.abc import ResourceReader
ResourceReader.register(_ZipImportResourceReader)
_ZipImportResourceReader._registered = True
return _ZipImportResourceReader(self, fullname)
return f'<zipimporter object "{self.archive}{path_sep}{self.prefix}">'
# _zip_searchorder defines how we search for a module in the Zip
# archive: we first search for a package __init__, then for
# non-package .pyc, and .py entries. The .pyc entries
# are swapped by initzipimport() if we run in optimized mode. Also,
# '/' is replaced by path_sep there.
(path_sep + '__init__.pyc', True, True),
(path_sep + '__init__.py', False, True),
# Given a module name, return the potential file path in the
# archive (without extension).
def _get_module_path(self, fullname):
return self.prefix + fullname.rpartition('.')[2]
# Does this path represent a directory?
# See if this is a "directory". If so, it's eligible to be part
# of a namespace package. We test by seeing if the name, with an
# appended path separator, exists.
dirpath = path + path_sep
# If dirpath is present in self._files, we have a directory.
return dirpath in self._files
# Return some information about a module.
def _get_module_info(self, fullname):
path = _get_module_path(self, fullname)
for suffix, isbytecode, ispackage in _zip_searchorder:
if fullpath in self._files:
# _read_directory(archive) -> files dict (new reference)
# Given a path to a Zip archive, build a dict, mapping file names
# (local to the archive, using SEP as a separator) to toc entries.
# A toc_entry is a tuple:
# (__file__, # value to use for __file__, available for all files,
# # encoded to the filesystem encoding
# compress, # compression kind; 0 for uncompressed
# data_size, # size of compressed data on disk
# file_size, # size of decompressed data
# file_offset, # offset of file header from start of archive
# time, # mod time of file (in dos format)
# date, # mod data of file (in dos format)
# crc, # crc checksum of the data
# Directories can be recognized by the trailing path_sep in the name,
# data_size and file_offset are 0.
def _read_directory(archive):
fp = _io.open_code(archive)
raise ZipImportError(f"can't open Zip file: {archive!r}", path=archive)
fp.seek(-END_CENTRAL_DIR_SIZE, 2)
header_position = fp.tell()
buffer = fp.read(END_CENTRAL_DIR_SIZE)
raise ZipImportError(f"can't read Zip file: {archive!r}", path=archive)
if len(buffer) != END_CENTRAL_DIR_SIZE:
raise ZipImportError(f"can't read Zip file: {archive!r}", path=archive)
if buffer[:4] != STRING_END_ARCHIVE:
# Bad: End of Central Dir signature
# Check if there's a comment.
raise ZipImportError(f"can't read Zip file: {archive!r}",
max_comment_start = max(file_size - MAX_COMMENT_LEN -
fp.seek(max_comment_start)
raise ZipImportError(f"can't read Zip file: {archive!r}",
pos = data.rfind(STRING_END_ARCHIVE)
raise ZipImportError(f'not a Zip file: {archive!r}',
buffer = data[pos:pos+END_CENTRAL_DIR_SIZE]
if len(buffer) != END_CENTRAL_DIR_SIZE:
raise ZipImportError(f"corrupt Zip file: {archive!r}",
header_position = file_size - len(data) + pos
header_size = _unpack_uint32(buffer[12:16])
header_offset = _unpack_uint32(buffer[16:20])
if header_position < header_size:
raise ZipImportError(f'bad central directory size: {archive!r}', path=archive)
if header_position < header_offset:
raise ZipImportError(f'bad central directory offset: {archive!r}', path=archive)
header_position -= header_size
arc_offset = header_position - header_offset
raise ZipImportError(f'bad central directory size or offset: {archive!r}', path=archive)
# Start of Central Directory
raise ZipImportError(f"can't read Zip file: {archive!r}", path=archive)
raise EOFError('EOF read where not expected')
if buffer[:4] != b'PK\x01\x02':
break # Bad: Central Dir File Header
raise EOFError('EOF read where not expected')
flags = _unpack_uint16(buffer[8:10])
compress = _unpack_uint16(buffer[10:12])
time = _unpack_uint16(buffer[12:14])
date = _unpack_uint16(buffer[14:16])
crc = _unpack_uint32(buffer[16:20])
data_size = _unpack_uint32(buffer[20:24])
file_size = _unpack_uint32(buffer[24:28])
name_size = _unpack_uint16(buffer[28:30])
extra_size = _unpack_uint16(buffer[30:32])
comment_size = _unpack_uint16(buffer[32:34])
file_offset = _unpack_uint32(buffer[42:46])
header_size = name_size + extra_size + comment_size
if file_offset > header_offset:
raise ZipImportError(f'bad local header offset: {archive!r}', path=archive)
file_offset += arc_offset
name = fp.read(name_size)
raise ZipImportError(f"can't read Zip file: {archive!r}", path=archive)
if len(name) != name_size:
raise ZipImportError(f"can't read Zip file: {archive!r}", path=archive)
# On Windows, calling fseek to skip over the fields we don't use is
# slower than reading the data because fseek flushes stdio's
# internal buffers. See issue #8745.
if len(fp.read(header_size - name_size)) != header_size - name_size:
raise ZipImportError(f"can't read Zip file: {archive!r}", path=archive)
raise ZipImportError(f"can't read Zip file: {archive!r}", path=archive)
# UTF-8 file names extension
# Historical ZIP filename encoding
name = name.decode('ascii')
except UnicodeDecodeError:
name = name.decode('latin1').translate(cp437_table)
name = name.replace('/', path_sep)
path = _bootstrap_external._path_join(archive, name)
t = (path, compress, data_size, file_size, file_offset, time, date, crc)
_bootstrap._verbose_message('zipimport: found {} names in {!r}', count, archive)
# During bootstrap, we may need to load the encodings
# package from a ZIP file. But the cp437 encoding is implemented
# in Python in the encodings package.
# Break out of this dependency by using the translation table for
# ASCII part, 8 rows x 16 chars
'\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f'
'\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f'
# non-ASCII part, 16 rows x 8 chars
'\xc7\xfc\xe9\xe2\xe4\xe0\xe5\xe7'
'\xea\xeb\xe8\xef\xee\xec\xc4\xc5'
'\xc9\xe6\xc6\xf4\xf6\xf2\xfb\xf9'
'\xff\xd6\xdc\xa2\xa3\xa5\u20a7\u0192'
'\xe1\xed\xf3\xfa\xf1\xd1\xaa\xba'
'\xbf\u2310\xac\xbd\xbc\xa1\xab\xbb'
'\u2591\u2592\u2593\u2502\u2524\u2561\u2562\u2556'
'\u2555\u2563\u2551\u2557\u255d\u255c\u255b\u2510'
'\u2514\u2534\u252c\u251c\u2500\u253c\u255e\u255f'
'\u255a\u2554\u2569\u2566\u2560\u2550\u256c\u2567'
'\u2568\u2564\u2565\u2559\u2558\u2552\u2553\u256b'
'\u256a\u2518\u250c\u2588\u2584\u258c\u2590\u2580'
'\u03b1\xdf\u0393\u03c0\u03a3\u03c3\xb5\u03c4'
'\u03a6\u0398\u03a9\u03b4\u221e\u03c6\u03b5\u2229'