pass arguments from Java to Python app

Hello readers,

I had a question by chris thompson on one of my previous posts, where I described in a short way how you can start a python script from your Java application (Link to comment), so I though, well lets face that. I basically referrer to my previous post but I adjusted some points:

First the python script. Create a new file “~/python/inputExample.py” with the following content:

import argparse

parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('integers', metavar='N', type=int, nargs='+',
help='an integer for the accumulator')
parser.add_argument('--sum', dest='accumulate', action='store_const',
const=sum, default=max,
help='sum the integers (default: find the max)')

args = parser.parse_args()
print args.accumulate(args.integers)

If you are curious, I took the parse input example from here: http://docs.python.org/library/argparse.html#module-argparse and well, as I
understood the question is more how can you pass arguments provided to the java app right to the python script.

So here we go:

package org.norbert;

import java.io.*;

public class PythonCallerInput {

/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
// set up the command and parameter
String pythonScriptPath = "/home/norbert/python/inputExample.py";
String[] cmd = new String[2 + args.length];
cmd[0] = "python";
cmd[1] = pythonScriptPath;
for(int i = 0; i < args.length; i++) {
cmd[i+2] = args[i];
}

// create runtime to execute external command
Runtime rt = Runtime.getRuntime();
Process pr = rt.exec(cmd);

// retrieve output from python script
BufferedReader bfr = new BufferedReader(new InputStreamReader(pr.getInputStream()));
String line = "";
while((line = bfr.readLine()) != null) {
// display each output line form python script
System.out.println(line);
}
}
}

So what is this doing? It is basically the same as in the other post, but we have to read and pass the parameters provided to the Java application to the Python script. Since the package I use in the python script is not available in python2.6, I invoke a call to “python”, which is in my case python version 2.7.2

We prepare the String array cmd by creating an array that can hold the command “python”, the path to our script and all arguments the you pass to the Java application. In the following for loop we copy all arguments from args to cmd to have them passed in rt.exec(cmd). Of course if you have security concerns you should perform checks on the user input before passing it to your script, but that’s another story. The rests stays the same, so read the response of python using a BufferedReader.

The output generated by the script is then read line by line with a BufferedReader and displayed in the terminal where we execute the java application.

You can execute the java program in eclipse by click on the green run button or compile and exec it in a terminal with:

cd workspace/JavaPythonCall/src/org/norbert
javac PythonCallerInput.java
cd ../..
java org.norbert.PythonCallerInput 1 2 3 4 --sum

result, yeah it calculates the sum of all provided integers, so this should be 10 😀

Ok, I hope this helps you chris

cheers
norbert

Advertisements

One thought on “pass arguments from Java to Python app

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s