5 Ways of Calling Java from Python

Some of my notes on calling Java from Python, only lightly edited from the raw notes. Short, mostly installation script and hello world code, but should serve the purpose.

Short answer: Jpype works pretty well, but Pyjnius is faster and
simpler than JPype

Summary

2013-05-21T22:38:11 (PDT) Pyjnius is faster and simpler than JPype

  • JCC, javabridge, Jpype and Jnius are all JNI wrappers.

2012-06-14T10:33:00 (PDT) Jpype works pretty well. I can call Stanford parser and OpenNLP from Python

2012-05-05T17:57:57 (PDT) close for now. At lease I can use Jpype. Reopen a Py4j task in the future if Jpype is not enough

Resources mentioned in this post are listed as visual bookmarks on Memect

 

javabridge

https://pypi.python.org/pypi/javabridge https://github.com/CellProfiler/python-javabridge/ http://pythonhosted.org/javabridge/ 

Install
sudo pip install javabridge

If fail https://github.com/CellProfiler/python-javabridge/issues/5

readlink -f `which java`
locate libjvm.so
sudo  update-alternatives --config java

cd /usr/lib
sudo ln -s /usr/lib/jvm/java-7-oracle/jre/lib/i386/client/libjvm.so
sudo pip install git+https://github.com/CellProfiler/python-javabridge

 

import os
import javabridge

javabridge.start_vm(['-Djava.class.path=' + os.pathsep.join(javabridge.JARS)],
 run_headless=True)
try:
 print javabridge.run_script('java.lang.String.format("Hello, %s!", greetee);',
 dict(greetee='world'))
finally:
 javabridge.kill_vm()

Jpype

http://jpype.sourceforge.net/

Install Jpype

sudo apt-get install python-jpype # Ubuntu

Or download exe installer from http://sourceforge.net/projects/jpype/files/JPype/0.5.4/ # Windows

Read more:

Tested on Windows

from jpype import *
 
startJVM("C:/Program Files/Java/jre6/bin/client/jvm.dll", "-ea")
 
# Java code here
# Create a java.lang.String object
javaPackage = JPackage("java.lang")
javaClass = javaPackage.String
javaObject = javaClass("Hello, Jpype")
 
# print the object
java.lang.System.out.println(javaObject)
# call String.length() and Integer.toString() methods
java.lang.System.out.println("This string's length: " +
 javaPackage.Integer.toString(javaObject.length()))
 
shutdownJVM()

gives

Hello, Jpype
This string's length: 12

Py4J

Install Py4J

easy_install Py4J
from py4j.java_gateway import JavaGateway

gateway = JavaGateway()
timestamp = gateway.jvm.System.out.println("Hello Py4j")

Error

socket.error: [Errno 10061] No connection could be made because the target machine actively refused it

Reason: Need Java GatewayServer

Read: http://py4j.sourceforge.net/getting_started.html

Write a small Java hello world:

import py4j.GatewayServer;

public class hello {

 public static void main(String[] args) {
 System.out.println("Hello, World");
 }
}

Run

javac hello.java -cp py4j0.7.jar
java hello -cp py4j0.7.jar hello.class

Py4j is a bit hard to use, as you need to start a gateway, adding another layer of fragility, so I decided not using it.

JCC

JCC is a C++ code generator for producing the code necessary to call into Java classes from CPython via Java’s Native Invocation Interface (JNI).

sudo apt-get install jcc

Compile a Java jar file into a Python module:
python -m jcc \
    --jar boilerpipe-1.2.0.jar \
    --classpath lib/nekohtml-1.9.13.jar \
    --classpath lib/xerces-2.9.1.jar \
    --package java.net java.net.URL \
    --python boilerpipe --build --install</pre>
<pre>
Use
</pre>
<pre>import boilerpipe
jars = ':'.join(('lib/nekohtml-1.9.13.jar', 'lib/xerces-2.9.1.jar'))
boilerpipe.initVM(boilerpipe.CLASSPATH+':'+jars)
extractor = boilerpipe.ArticleExtractor.getInstance()
url = boilerpipe.URL('http://readthedocs.org/docs/jcc')
extractor.getText(url)[:24]
# u'Download boilerpipe from'
2013-03-30T11:49:19 (PDT) try on Ubuntu 12.10, succeed
svn co http://svn.apache.org/repos/asf/lucene/pylucene/trunk/jcc jcc
cd jcc
pico setup.py
# 'linux2': '/usr/lib/jvm/java-7-oracle', # or your version of Java
python setup.py build
sudo python setup.py install
Test
cd ~ && python    # make sure leave the jcc installation folder
>>> import jcc

Pyjnius

2013-05-21T21:08:38 (PDT) Python module to access Java class as Python class, using JNI

http://pyjnius.readthedocs.org/en/latest/index.html

https://github.com/kivy/pyjnius

sudo pip install cython jnius

Install from source

sudo pip install git+git://github.com/kivy/pyjnius.git

2013-05-22T00:18:14 (PDT) note: install 1.1-dev from source works, default pip install is 1.0.2 and is not working

Example

from jnius import autoclass
Stack = autoclass('java.util.Stack')
stack = Stack()
stack.push('hello')
stack.push('world')
stack.pop()
# 'world'
stack.pop()
# 'hello'

Some resources mentioned in this post http://memect.co/python-java

python java   Python