Friday, March 30, 2007

Standalone Jython — ImportError: no module named awt

I've spent probably about a day figuring out what's going on here, Google being no help whatsoever, so figure I might as well publish.

Scenario -- Jython 2.2b1, installed in standalone mode i.e. all of /Lib inside the jar, and cachedir being skipped.

Now this sort of code works with Jython launched from the jar in the standard install:

but with Jython.jar from the standalone the code gives

C:\jython2.2b1-standalone>java -jar jython.jar
Jython 2.2b1 on java1.6.0 (JIT: null)
Type "copyright", "credits" or "license" for more information.
>>> import java.awt
Traceback (innermost last):
  File "", line 1, in ?
ImportError: no module named awt
>>> ^Z

Hunting down the error message, it is raised in org.python.core.imp, ultimately from JavaImportHelper.tryAddPackage() failing. Meanwhile, from the other direction, doing

import sys

gave me that sys has a packageManager attribute. And that has a makeJavaPackage method. This lives in org.python.core.PackageManager

So, that seemed worth giving a try. Like

And that, at last, worked.

Now, you might think it would be elegant to do something like

to allow for the cases where it would work anyway; but this doesn't work -- the branch is taken, but the conditional packaging doesn't seem to stick. However, it doesn't seem to matter if you always explicitly add the package as part of the initialisation, even when not strictly needed. So stick with the simple case. It's more Pythonic that way, after all.


Oti said...

Let me describe 2 ways of doing it, both using explicit java class imports.

from java.awt import Frame
frame = Frame()

3. (only available with a release > 2.2b2)
import java.awt.Frame
frame = java.awt.Frame()

Robert Dodier said...

I find that putting stuff into the boot classpath enables Jython to find the classes. E.g. say I have mystuff.jar, then I start Jython via

$ java -Xbootclasspath/a:mystuff.jar (usual-options-here)

Then in Jython, I can enter

>>> import mystuff.MyClass

Without the -Xbootclasspath, I find that Jython complains about "mystuff" being a missing package, even if mystuff.jar is in $CLASSPATH or specified via -cp or -classpath.

Hope this helps someone.

Unknown said...

You can also edit the Jython registry file and add specific .jar files to the python.path

Seems odd but it works.

Anonymous said...

hi guys
i have a Q about this issue...
i try to run a jython script via another scripting tool. this tool is WEbSphere's (wsadmin). i want a jython file to use (to import) another jython file with class definitions. so i actually write:
wsadmin -f ""
and in i have import to
but i guess it has its own classpath or something... anyway, i tried to do what is written here and it didnt help. i tried to put my into a jar and add this jar to the classpath but it didnt help either
anyone has an idea?