1

I have a Java app that takes a long time to be initialized (so I can't use a command-line like interface) and I need to pass text and receive the output of a Java method from Python. Is it possible to load the Java application, have it open all the time the Python script runs and use a method from that app?

2
  • 1
    If you are running Jython it is easy Commented May 3, 2010 at 15:48
  • +1 for Jython. It's seamless to use Java from within the Jython interpreter. Commented May 3, 2010 at 16:34

4 Answers 4

2

I don't think the use of Python helps all that much over a command line (at least not a *nix command line), but the basic idea is to communicate over a socket or some similar mechanism. That means that the Java application will have to be wrapped in some code which opens a socket and waits for the python script to contact it. If you are most comfortable with python, you could look to implement that wrapper in Jython.

Sign up to request clarification or add additional context in comments.

Comments

0

I've used JPype for something similar and it worked great.

JPype is an effort to allow python programs full access to java class libraries. This is achieved not through re-implementing Python, as Jython/JPython has done, but rather through interfacing at the native level in both Virtual Machines.

If the java app is running you should also consider xml-rpc as it also works well.

Comments

0

Py4J is a way to call Java from a python script. Here is the project website: http://py4j.sourceforge.net/

Comments

0

[ Disclaimer: I am the primary maintainer of PJRmi ]

PJRmi is one of the libraries which provides support for calling into Python; others are:

  • py4j allows Python to call into Java. It also supports Java calling back into Python so that Python clients can implement Java interfaces. It works by communicating over a socket.

  • jpy is another in-process implementation. One of its key features is support for fast pass-by-value operations with arrays by use of pointer hand-off.

  • jpype is another in-process implementation. Since it also uses internal C-based handoff it's highly performant.

  • PyJNIus is another implementation which accesses Java classes using JNI.

A simple example of calling into Java from Python, where the Java process is long-lived, would look like:

>>> import pjrmi
>>> c = pjrmi.connect_to_child_jvm()
>>> HashMap = c.javaclass.java.util.HashMap
>>> m = HashMap(dict((str(i), i+1) for i in range(5)))
>>> m.get("3")
4

Which one of the various versions of the Python/Java bridges you like depends upon your use-case. Ones which use direct JNI for hand-off (like JPype) tend to be very fast but might limit you to a single Java instance per invocation.

1 Comment

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.