call python script from Java app

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.norbert;

import java.io.*;

public class PythonCaller {

/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
// set up the command and parameter
String pythonScriptPath = "/home/norbert/python/helloPython.py";
String[] cmd = new String[2];
cmd[0] = "python"; // check version of installed python: python -V
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
System.out.println(line);
}
}
}

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:

cd workspace/JavaPythonCall/src/org/norbert
javac PythonCaller.java
cd ../..
java org.norbert.PythonCaller

result:

Hello World from python

Sweet ^_^ yeah πŸ˜‰ This was a quick one, but I hope this helps.
cheers
norbert

Advertisements

10 thoughts on “call python script from Java app

    • Yeah, I try to focus in my posts on the main aspects. I also don’t like to read a lot of blabla before someone comes to the point you know πŸ˜‰

  1. It is throwing error:
    java.lang.NoClassDefFoundError: systemLevel/ExecutePython
    Caused by: java.lang.ClassNotFoundException: systemLevel.ExecutePython
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    Exception in thread “main”

    My Code is :
    package systemLevel;

    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    public class ExecutePyton1 {

    /**
    * @param args
    */
    public static void main(String[] args) {

    Runtime runTime=Runtime.getRuntime();
    try {
    String pythonScriptPath=”F:\\python\\hello1.py”;
    String[] cmd=new String[2];
    cmd[0]=”c:\\Python27\\python.exe”;
    cmd[1]=pythonScriptPath;
    Process process=runTime.exec(cmd);

    BufferedReader bfr=new BufferedReader(new InputStreamReader(process.getInputStream()));
    String line=””;
    while((line=bfr.readLine())!=null){
    System.out.println(line);
    }
    } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    }
    }

    • Hello Shivam,
      here are some adivce how you can pinpoint and fix the error:

      1) check indents in hello1.py
      this simple hello world needs no indents

      2) check your spelling:
      ExecutePyton1.java or
      ExecutePython1.java ?
      java “public class CLASSNAME” and file name have to be identical!
      this is also important for compiling and executing
      the error messages seems to point to the fact, that your java class cannot be found
      check by compiling manually (see below)

      3) check folder structure:
      start with this: everything in one folder
      systemLevel/ExecutePyton1.java
      systemLevel/ExecutePyton1.class
      systemLevel/hello1.py

      3.1) check path declaration for hello1.py and python.exe, upper and lower letters may cause problems. Double-Backslashes seem to be fine, as far as I know. Since I am on linux, I cannot provide more help on Windows, sorry.

      4) check if your python programm runs smoothly:
      python systemLevel/hello1.py
      output should be “hello world” or something similar

      5) compile java programm:
      javac systemLevel.ExecutePyton1.java

      6) execute java programm:
      java systemLevel.ExecutePython
      output should again be “Hello World” or the text your python programm prints.

      if that works, you can move your python script to another folder, like F:\\….

  2. package org.norbert;

    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;

    public class pythoncaller {

    /**
    * @param args
    * @throws IOException
    */
    public static void main(String[] args) throws IOException {
    // set up the command and parameter
    /*String pythonScriptPath = “/home/norbert/python/helloPython.py”; */
    String pythonScriptPath = “C:/Users/310032493/workspace/PKM1/src/org/norbert/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
    System.out.println(line);
    }
    }
    }

    It says

    Exception in thread “main” java.io.IOException: Cannot run program “python2.6”: CreateProcess error=2, The system cannot find the file specified
    at java.lang.ProcessBuilder.start(Unknown Source)
    at java.lang.Runtime.exec(Unknown Source)
    at java.lang.Runtime.exec(Unknown Source)
    at org.norbert.pythoncaller.main(pythoncaller.java:23)
    Caused by: java.io.IOException: CreateProcess error=2, The system cannot find the file specified
    at java.lang.ProcessImpl.create(Native Method)
    at java.lang.ProcessImpl.(Unknown Source)
    at java.lang.ProcessImpl.start(Unknown Source)
    … 4 more

    • Hello Krishna,
      thanks for your feedback on this (quite old) blog post from me πŸ™‚
      I had a look at the error message you posted, and I think that you maybe have installed a later version of python then I was using when I wrote this blog entry.
      Please check the version of your installed python (python -V), it maybe is version 2.7.6 or even version 3.x
      Anyway, if you have python installed, you can change the command in line 15 from “python2.6” to “python” … this should work.
      Best wishes
      norbert

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