Jython: Packing several .py on .jar, problem importing .py modules within the .jar

Gubatron gubatron at gmail.com
Wed Dec 3 06:31:13 EST 2008


Hello all,

I've a problem with Jython and importing .py inside a jar.

I'm putting .class and .py files inside .jar files.

myjar.jar
  MyJar\SomeClass.class
  MyJar\main.py
  MyJar\otherModule.py

So I add the myjar.jar to Jython's sys.path

                        org.python.core.PySystemState pySys = new
org.python.core.PySystemState();
			pySys.path.insert(0,new PyString("/path/to/myjar.jar"));

and execute main.py

			//We pass the PythonInterpreter the modified PySystemState
			PythonInterpreter i = new PythonInterpreter(null, pySys);

			//Find the entry in the jar for the python file and execute it.
			//It should be able to find any resource inside the jar.
			JarFile jFile = new JarFile("/path/to/myjar.jar");
			ZipEntry zipEntry = jFile.getEntry("MyJar/main.py");

                        InputStream pythonInputStream =
jFile.getInputStream(zipEntry);
                        i.execfile(pythonInputStream);

main.py will execute fine, it'll be able to do

from MyJar import SomeClass

with no problem

However, If I try to import the other .py in the same jar, it won't
find it:

from otherModule import *

or

from MyJar.otherModule import *

I always get this:

ImportError: no module named otherModule

        at org.python.core.Py.ImportError(Unknown Source)
        at org.python.core.imp.import_first(Unknown Source)
        at org.python.core.imp.import_name(Unknown Source)
        at org.python.core.imp.importName(Unknown Source)
        at org.python.core.ImportFunction.load(Unknown Source)
        at org.python.core.ImportFunction.__call__(Unknown Source)
        at org.python.core.PyObject.__call__(Unknown Source)
        at org.python.core.__builtin__.__import__(Unknown Source)
        at org.python.core.imp.importFromAs(Unknown Source)
        at org.python.core.imp.importFrom(Unknown Source)
        at org.python.pycode._pyx1.f$0(<iostream>:26)
        at org.python.pycode._pyx1.call_function(<iostream>)
        at org.python.core.PyTableCode.call(Unknown Source)
        at org.python.core.PyCode.call(Unknown Source)
        at org.python.core.Py.runCode(Unknown Source)
        at org.python.util.PythonInterpreter.execfile(Unknown Source)

I've tried adding more paths to sys.path, with no luck:

pySys.path.insert(0,new PyString("/path/to/myjar.jar/MyJar"));
pySys.path.insert(0,new PyString("file:jar:/path/to/myjar.jar!"));

and nothing works, any ideas would help. I know this has to work,
because I previously had a problem where I couldn't do

import os

and then I added the "Lib/" folder inside jython.jar and now I'm able
to import all those standard jython modules, so, somehow, jython is
able to import .py within a .jar, help would be very much appreciated.

Angel Leon



More information about the Python-list mailing list