Using Python within Java

There are interoperability options abounding these days, and Python is part of the trend. On the Java side, Jython has emerged as a useful bridging mechanism. Daniel Rubio describes some basics in employing Python within Java, which can be useful for developers that may stand to benefit from Python’s aptness for expressing some logic. - JV

By Daniel Rubio

Java’s syntax and APIs are often considered deep and extensive, in fact, even seasoned developers find themselves continuously learning new ways to get things done faster. But on occasions, if viewed from outside Java’s own monoculture, there are often many easier routes to express the same logic in different languages.

Up next, we will take a look at how you can enjoy some of Python’s functionality straight from within Java and benefit from this interoperability bridge, in the process gaining from the former language’s syntax and idioms.

The first thing you will need to do besides having Python and Java on your server or workstation is install Jython, which provides the actual bridge in the form of a Jar file and configuration hooks to invoke both environments from one another.
 
Our task at hand will consist of reading two text files containing first and last names and later creating a list of permutations with these values using Python’s core API, all from within a Java. Listing 1.1 shows how our Java class would be structured.

Listing 1.1 Java class invoking Python logic
import org.python.core.PyObject;
import org.python.core.PyException;
import org.python.util.PythonInterpreter;

public class Interop {
  public static void main(String []args) throws PyException {

    PythonInterpreter interp = new PythonInterpreter();
    interp.exec(”firstNames=open(’/tmp/FirstNames.txt’,'r’)”);
    interp.exec(”lastNames=open(’/tmp/LastNames.txt’,'r’)”);
    interp.exec(”fNlines=firstNames.readlines()”);
    interp.exec(”lNlines=lastNames.readlines()”);
    interp.exec(”fullNames=[x+y for x in fNlines for y in lNlines]”);
    PyObject completeList = interp.get(”fullNames”);

    System.out.println("Full names : "+ completeList);
  }
}
[End Listing 1.1]

If you execute this last class you will see a list with all the possible combinations of first names included in a file located at /tmp/FirstNames.txt, and last names included in a file placed at /tmp/LastNames.txt. Note that similarly to any other Java class, you will need to include Jython’s Jar file in your Java classpath at both compile-time and run-time.

Within the Java class itself, notice how we use import statements to access classes included in Jython’s distribution, which then allows us to invoke Python statements. Among the main classes you will find PythonInterpreter that, accompanied by its exec method, invokes the actual Python instructions. Interspersed through the Java class you will also observe PyObject, which is used for representing a Python object inside Java.

The sequence contained within the interp.exec declarations — which performs the actual logic — proves to be interesting because it offers a simpler approach to its equivalent in Java. Granted Java has its own file reading classes and looping idioms, but Python’s succinctness in these two tasks is evident.

Still, let’s assume you aren’t blown away by these Python core features, Python offers a rich set of developments which may provide you with a simpler and often more powerful set than those offered in Java. I’ve personally found Universal FeedParser and BeatuifulSoup as two Python projects which excel at processing XML data feeds and markup content, especially when compared to the lengthier DOM and SAX techniques offered in Java.

Like many other interoperability options, its not that you will be using Python to oust every single line of Java in your project, its simply another option you can add to your knowledge arsenal, which under certain circumstances can help you get things done faster and easier than what you may currently have at your fingertips using Java.


Leave a Reply