Home » , » Mixing Java and Python

Mixing Java and Python

1. Invoking python script from Java 



import java.io.*;

public class Foo

{
    public static void main(String[] args)
    {
        try
        {
            Runtime r = Runtime.getRuntime();
            Process p = r.exec("python foo.py");
            BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
            p.waitFor();
            String line = "";
            while (br.ready())
                System.out.println(br.readLine());

        }

        catch (Exception e)
        {
String cause = e.getMessage();
if (cause.equals("python: not found"))
System.out.println("No python interpreter found.");
        }
    }
}

The only problem with this method is that it requires the user to have a python interpreter installed on their system (and in the PATH). 


A solution for this problem is to install jython as a jar file and now I can just invoke it by including it in my class path. Here is a sample file: 



import org.python.util.PythonInterpreter;

public class Foo

{
public static void main (String[] args)
{
try
{
PythonInterpreter.initialize(System.getProperties(), System.getProperties(), new String[0]);
PythonInterpreter interp = new PythonInterpreter();
interp.execfile("foo.py");
}
catch (Exception e)
{
e.printStackTrace();
}
}
}

Note: Just make sure jython.jar is in your classpath. 



Inter-process communication of Java and Python

2. Using Socket 

3. Using jsonrpc

JSON-RPC + IDL = Barrister RPC 
This is simple. Just define your interface in a human readable IDL. 
Actually, this is the one I ended up with. 

In my cases, I use python code in the http server (Flask), and java as the client. 

The best thing is you even do not have to write any codes to call the python codes. 
Barrister RPC does everything for you since it could generate all the client codes automatically according the contract defined in the IDL. In addition, you do not have to do the data format conversion yourself. That is tedious. Barrister also does this for you in its automatically generated codes. Really cool, isn't it? 



other solutions can be found in the following presentation: 


http://elib.dlr.de/59394/1/Mixing_Python_and_Java.pdf






Popular Posts