Hustle Play

Syd's blog.

JPype Tutorial

Today, I used JPype to execute some Java code that I did not want to re-implement.

JPype allows you to start a JVM inside your Python program. This is useful when you want put minimal effort into combining existing Java source code with Python. With a few simple lines, you can start the JVM, do your everyday Java activities, and then close the JVM when you’re done.

Here is a a simple ‘Hello World’ program:

from jpype import *

startJVM("d:/tools/j2sdk/jre/bin/client/jvm.dll", "-ea")

java.lang.System.out.println("Hello World")

shutdownJVM()

Let’s go through the code line by line. The first line is how you access(import) the jpype utilities. That is simple enough…

In the second line, you start the JVM using the startJVM function. You pass this function the path to your jvm.dll (in Windows). The second argument is a String which you can use to add any JVM options you want. A pretty comprehensive list of JVM options can be found here. You use this option to add directories to your Java classpath as well (more on this below).

The third line shows you how to call System.out.println(). Note that this is actually calling jpype.java.lang.System.out.println(). For convenience purposes, the java and javax packages are included in jpype. Any other packages need to be accessed using the jpype.JPackage class (more on this below).

The fourth and last line shows how to shut down the JVM with the shutdownJVM function. When this function executes, you get a short printout which summarizes the activities that took place during the JVM session. I’m not sure how to turn this off, but it’s not too annoying yet.

Now we’ll go through a slightly more difficult example where we use a piece of Java code that we write ourselves.

Here is the Java code:

package org.wg3i.test;

public class Test {
    private String msg;

    public Test() {
        msg = "nothing so far...";
    }

    public static void speak(String msg) {
        System.out.println(msg);
    }

    public void setString(String s) {
        msg = s;
    }

    public String getString() {
        return msg;
    }
}

And here is the Python code:

from jpype import *

startJVM("C:\\Program Files\\Java\\jdk1.6.0_05\\jre\\bin\\client\\jvm.dll", "-ea -Djava.class.path=C:\\Documents and Settings\\Sydney\\Desktop\\jpypeTest\\")

testPkg = JPackage('org').wg3i.test
Test = testPkg.Test

Test.speak("hi")
t = Test()
print t.getString()

shutdownJVM()

To run this example, you first have to compile the Java source code with javac. Then place the .class file in the (current_directory)/org/wg3i/test/ directory. Then run the Python script.

If you do not place the .class file correctly in the directory structure that is specified by it’s package name, you may encounter a TypeError. Something like:

"TypeError: Package org.wg3i.test.Test is not Callable "

I got hung up on this for a little bit.

Reference(s):

See Also:

5 responses to “JPype Tutorial

  1. Mahasen July 28, 2010 at 2:35 am

    hi, I try this in debian 5 but does not work.

    startJVM(“/usr/lib/jvm/default-java/jre/lib/i386/client/libjvm.so”, “-ea”)

    get an error..

    Traceback (most recent call last):
    File “”, line 1, in
    jpype.startJVM(“/usr/lib/jvm/default-java/jre/lib/i386/client/libjvm.so”, “-ea”)
    File “/usr/lib/pymodules/python2.5/jpype/_core.py”, line 44, in startJVM
    _jpype.startup(jvm, tuple(args), True)
    RuntimeError: An unknown error occured while handling a Java Exception

  2. nyomz August 21, 2010 at 7:17 am

    thanks…
    its helpful for me..

  3. ds1 October 11, 2010 at 11:19 am

    Question: If my Java class has a method named ‘exec’, how can I call this? My code is as follows:

    d = JPackage( ‘com’ ).disc
    client = d.DiscClient()
    service = client.getService( “TQ” )
    u = service.exec( “select * from emp” )

    I get an invalid syntax error on exec. Anybody have any ideas?

    • JimK June 21, 2011 at 12:26 pm

      import operator
      exec_caller = operator.methodcaller(‘exec’, “select * from emp”)
      u = exec_caller(service)

      It’s ugly, but it may be the only way around the Python name clash.

  4. Pingback: using custom java classes with JPype: package not callable error | Zezima Answers

Leave a comment