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.




Leave comments

authimage
  • hi,
    i am able to call python script from java,i just want to know how to pass values to python from java script

    below is my python script,i want to restrict if condition only one time,

    python script :

    from com.android.monkeyrunner import MonkeyRunner, MonkeyDevice
    import time

    def egg(static={"count":0}):

    static["count"]+=1

    if static["count"] == 25:
    static["count"] = 2

    return static["count"]

    guess = egg()

    print guess

    number = 1

    if guess == number:
    print 'one time device connection - if condition executed'
    device = MonkeyRunner.waitForConnection()

    else:
    print 'No, else condition executed'
    result = device.takeSnapshot()
    # result.writeToFile('/home/its/Desktop/tests/shot1.png','png')

    • Abhilash
  • Hi Abhishek,
    i mentioned above to pass arguments to python script through java programming. If you want to call python script and pass argument to python script from javascript then i suggest you to use ajax and cgi module of python. put your script to cgi-bin folder and call it through ajax.

    • sharmavivek82
  • .

    • nobody
  • Hi,
    How to pass argument from java to python program, I can execute the program from java but I want to pass argment to python method…………………..?? I new to both java and python………………
    When I put some text in layerobj=javapython("name") and execute from java,it give that output………………….

    But when I passing argument from java………………………no output and no error as shown here………
    run:

    BUILD SUCCESSFUL (total time: 0 seconds)
    Note: i using pyhton 2.6............
    Thanks in advance

    +++++++++++++++++++++++++++++++++++++++++
    “test.py”

    class javapython:
    def __init__(self,layer):
    self.layer=layer
    print layer

    layerobj=javapython("")

    *******************************************java program**********************

    package javapy;
    import java.io.*;

    public class javatopython {
    public static void main(String args[]) {

    String st = null;

    try {

    String[]callAndArgs={"C:\\Python26\\python.exe","D:\\pythonmapfile\\mapcreation\\mapscriptmap\\test.py","testnameargument"};

    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 ((st = stdInput.readLine()) != null) {

    System.out.println(st);

    }

    // read any errors

    while ((st = stdError.readLine()) != null) {

    System.out.println(st);

    }
    System.exit(0);

    }

    catch (IOException e) {

    System.out.println("exception occured");

    e.printStackTrace();

    System.exit(-1);

    }

    }

    }

    • jan
  • i done after changing the python program.,............
    //**************************pyhton***************************
    import sys
    # take the first input argument
    mystring = sys.argv[1]
    print mystring
    //*****************************************java+++++++++++++++++++

    package javapy;
    import java.io.*;

    public class javatopython {
    public static void main(String args[]) {

    String st = null;
    String arg="hello";

    try {

    String[]callAndArgs={"C:\\Python26\\python.exe","D:\\pythonmapfile\\mapcreation\\mapscriptmap\\vaasxmlparsing2.py",arg};

    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 ((st = stdInput.readLine()) != null) {

    System.out.println(st);

    }

    // read any errors

    while ((st = stdError.readLine()) != null) {

    System.out.println(st);

    }


    System.exit(0);

    }

    catch (IOException e) {

    System.out.println("exception occured");

    e.printStackTrace();

    System.exit(-1);

    }

    }

    }

    • jan

Copyright(c) 2017 - PythonBlogs.com
By using this website, you signify your acceptance of Terms and Conditions and Privacy Policy
All rights reserved