Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Zipimport with packages

I'm trying to package the pychess package into a zip file and import it with zipimport, but running into some issues.

I've packaged it into a zipfile with the following script, which works:

#!/usr/bin/env python
import zipfile
zf = zipfile.PyZipFile('../pychess.zip.mod', mode='w')
try:
    zf.writepy('.')
finally:
    zf.close()
for name in zf.namelist():
    print name

However, I'm unable to do complicated imports in my code:

z = zipimport.zipimporter('./pychess.zip.mod')
#z.load_module('pychess') # zipimport.ZipImportError: can't find module 'pychess'
#z.load_module('Utils.lutils') # zipimport.ZipImportError: can't find module 'Utils.lutils'
Utils = z.load_module('Utils') # seems to work, but...
from Utils import lutils
#from Utils.lutils import LBoard  # ImportError: No module named pychess.Utils.const


How can I import, e.g. pychess.Utils.lutils.LBoard from the zip file?

Here is the full list of modules I need to import:

import pychess
from pychess.Utils.lutils import LBoard
from pychess.Utils.const import *
from pychess.Utils.lutils import lmovegen
from pychess.Utils.lutils import lmove

Thanks!

like image 229
tba Avatar asked Nov 04 '22 00:11

tba


1 Answers

Assuming you have an unpacked pychess, resulting in a pychess-0.10.1 directory in your current directory and that pychess-0.10.1/lib/pychess exists ( I got that directory from untarring pychess-0.10.1.tar.gz).

First run:

#!/usr/bin/env python

import os
import zipfile

os.chdir('pychess-0.10.1/lib')
zf = zipfile.PyZipFile('../../pychess.zip', mode='w')
try:
    zf.writepy('pychess')
finally:
    zf.close()
for name in zf.namelist():
    print name

after that, this works:

#!/usr/bin/env python

import sys
sys.path.insert(0, 'pychess.zip')

from pychess.Utils.lutils import LBoard
like image 141
Anthon Avatar answered Nov 15 '22 05:11

Anthon