Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I access a module from a package using Python's zipimport?

I wrote a simple Python package using python's paster, where my package has the directory structure:

pkg/
    __init__.py
    module1.py
    subpackage/
        __init__.py
        module2.py

The init.py files are blank and module1.py contains a function that imports something from module2.py. I install the package and I'm able to call functions in module1.py from the python prompt:

import pkg.module1

I go to where the package was installed (/usr/lib/python2.7/dist-packages/pkg/) and zip the pkg directory:

zip -r pkg.zip pkg/

I try to access the module from the python prompt using zipimport:

import zipimport
importer = zipimport.zipimporter('pkg.zip')
importer.find_module('pkg')
# <zipimporter object "pkg.zip">
importer.load_module('pkg')
# <module 'pkg' from 'pkg.zip/pkg/__init__.pyc'>
importer.is_package('pkg')
# True
pkg = importer.load_module('pkg')
# trying to call a function in module 1 called fcn1
pkg.module1.fcn1()
#Traceback (most recent call last):
#File "<stdin>", line 1, in <module>
#AttributeError: 'module' object has no attribute 'module1'
pkg.module1
#Traceback (most recent call last):
#File "<stdin>", line 1, in <module>
#AttributeError: 'module' object has no attribute 'module1'

Any ideas on how to access module1? Thanks.

like image 686
user1910316 Avatar asked Oct 15 '25 18:10

user1910316


2 Answers

Try the following:

import sys
sys.path.append('./pkg.zip') # Or path to pkg.zip
import module1

module1.fcn1()

This will use zipimport for you.

I think that you may need to list the public parts of your module in it's init.py file take a look at PEP 273

like image 181
Steve Barnes Avatar answered Oct 17 '25 07:10

Steve Barnes


You are missing a step. If your package was not in a zip file, you would do:

import pkg
import pkg.module1   # You did not do this.
result = pkg.module1.fnc1()

OR file contents of pkg\__init__.py could instead be:

import module1 # __init__.py does it for you.
like image 38
DevPlayer Avatar answered Oct 17 '25 08:10

DevPlayer