how to use jpype in python?
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:
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:
And here is the Python code:
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:
- Get the JPype source. The JPype source may be acquired from either github or from PyPi.
- Build the source with desired options. Compile JPype using the included setup.py script: python setup. py build.
- Test JPype with (optional): python setup. py test.
- Install JPype with: python setup. py install.