Hello readers,

in this post I wanna give you a brief description how you can call python code from with a java program. For that purpose we will use two very simple “Hello World” programs, one in python, one for java.

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

import os
from stat import*
print "Hello World from python"
Now fire up your eclipse and create a default java application. Create a new java class named “PythonCaller”. The content of this new file will look like this:
package org.deepak;
public class PythonCaller {
* @param args
* @throws IOException
public static void main(String[] args) throws IOException {
//setup the commandand parameter
String pythonScriptPath = "/home/deepak/python/helloPython.py";
String[] cmd = new String[2];
cmd[0] = "python2.6";
cmd[1] = pythonScriptPath;
//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

So what is this doing? Basically we execute the python script by envoking python2.6 and provide the path to the script as parameter, as you would normally do it if you exec the script in a terminal/bash.
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:

javac PythonCaller.java
java org.deepak.PythonCaller
Hello World from python
Sweet ^_^ yeah ;) This was a quick one, but I hope this helps.

2 thoughts on “call python script from Java 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 )

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s