Tutorial :Jython and python modules


I've just started using the PythonInterpreter from within my Java classes, and it works great! However, if I try to include python modules (re, HTMLParser, etc.), I'm receiving the following exception (for re):

  Exception in thread "main" Traceback (innermost last):    File "", line 1, in ?  ImportError: no module named re  

How could I make the classes from the jython jar "see" the modules python has available?


You embed jython and you will use some Python-Modules somewere:

if you want to set the path (sys.path) in your Java-Code :

public void init() {          interp = new PythonInterpreter(null, new PySystemState());            PySystemState sys = Py.getSystemState();          sys.path.append(new PyString(rootPath));          sys.path.append(new PyString(modulesDir));      }  

Py is in org.python.core.

rootPath and modulesDir is where YOU want !

let rootPath point where you located the standard-jython-lib

Have a look at src/org/python/util/PyServlet.java in the Jython-Source-Code for example


According to the FAQ:

4.1 What parts of the Python library are supported?

The good news is that Jython now supports a large majority of the standard Python library. The bad news is that this has moved so rapidly, it's hard to keep the documentation up to date.

Built-in modules (e.g. those that are written in C for CPython) are a different story. These would have to be ported to Java, or implemented with a JNI bridge in order to be used by Jython. Some built-in modules have been ported to JPython, most notably cStringIO, cPickle, struct, and binascii. It is unlikely that JNI modules will be included in Jython proper though.

If you want to use a standard Python module, just try importing it. If that works, you're probably all set. You can also do a dir() on the modules to check the list of functions it implements.

If there is some standard Python module that you have a real need for that doesn't work with Jython yet, please send us mail.

In other words, you can directly use Python modules from Jython, unless you're trying to use built-in modules, in which case you're stuck with whatever has been ported to Jython.


Check your jython sys.path . Make sure that the library you want to load are in this path. Look at jython faq for more details.


You can refer here for the solution Importing python modules in jython

Download ez_setup.py from here http://peak.telecommunity.com/dist/ez_setup.py

Then run jython ez_setup.py <any module name>.

Running it on any folder path doesn't matter.

I could install pymysql with it, no problem.

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »