November 1, 2006

Jepp: Script your Java applications with Python

Author: Mike Johnson

The Jepp project, which lets you use Python to access Java objects, has just packaged its 2.0 release, with added javax.script support, a new import feature, and other improvements.

Other scripting projects for Java suffer from problems such as slow interpretation, excessive bugs, or the need for an extensive knowledge of Java. By contrast, Python is a great language to give to former Visual Basic programmers. It's well-documented, mature, and quick to learn.

To give Jepp a try, download the source, untar it, then ./configure && make && make install. More specific instructions can be found in the README file included with the source.

Prebuilt binaries are available for Windows that require ActiveState Python 2.4. You can use other Python versions, but you'd need to compile your own DLL.

Once you've installed the software, run the console.py script to make sure everything is working. The console is also helpful when building quick prototypes and learning the Java API. Once again, check the README file for more documentation on running Python scripts.

$ java -jar jep.jar console.py
>>> from java.lang import *
>>> s = String('do crazy stuff')
>>> print String(s.toCharArray()[3:8])
crazy

This example creates a java.lang.String instance and converts it to a character array. Then it uses Python's slice support to create a new array of just the "crazy" characters. By constructing a new Java string from the array, it can then print the result.

Jepp will try to silently convert Python and Java values wherever possible. This makes using Jepp much like using native Python.

Features

Another interesting feature of Jepp is its ability to create new exception types on the fly. This feature can make exception processing somewhat expensive and can be disabled at compile time.

>>> from java.io import FileInputStream
>>> try:
...     FileInputStream('no such file')
... except(jep.FileNotFoundException):
...     print 'File not found.'
...
File not found.

Using Jepp from within Java is also easy. Consider the Java code:

Jep jep = new Jep();
jep.eval("print 'hello'");
jep.close();

Of course, this example is missing exception handling for the sake of clarity. Also note that, like anything that uses native resources in Java, Jepp needs to be closed.

Summary

Jepp is a great scripting solution for Java. It allows you the clarity and power of Python and access to high-quality Python extensions. Use Jepp from within Tomcat to add a scripting environment for business logic, or run your existing Python scripts from Java to add access to Java's libraries.

Mike Johnson is an active duty United States Marine who misses programming and Brother's Korean BBQ in San Francisco greatly. He wrote Jepp while working for Trinity Capital, a subdivision of Bank of the West, which generously allowed him to open source the work.

Category:

  • Java
Click Here!