Friday, August 20, 2010

Call Python script from Java.

I am not good at core java programming, but good at "Hello World" kind of program :) .
SO i wrote a Java program to call python script(can also pass arg values). Take a look.

This is Java code
    import java.io.*;

    // run this way
    // javac JavaRunCommand.java
    // java -classpath . JavaRunCommand

    public class JavaRunCommand {

        public static void main(String args[]) {

        String st = null;

        try {

            String[]callAndArgs= {"python","my_python.py","arg1","arg2"};
            Process p = Runtime.getRuntime().exec(callAndArgs);
           
            BufferedReader stdInput = new BufferedReader(new
                 InputStreamReader(p.getInputStream()));

            BufferedReader stdError = new BufferedReader(new
                 InputStreamReader(p.getErrorStream()));

            // read the output
            while ((s = stdInput.readLine()) != null) {
                System.out.println(s);
            }
           
            // read any errors
            while ((s = stdError.readLine()) != null) {
                System.out.println(s);
            }
           
            System.exit(0);
        }
        catch (IOException e) {
            System.out.println("exception occured");
            e.printStackTrace();
            System.exit(-1);
        }
        }
    }

In above java code, i am calling my_python.py script. That script might contain anything-wxPython, mod-python, cgi programming, just anything.

No comments: