using java to call and run python but no result. processbuilder runtime

418 Views Asked by At

I tried both runtime and processbuilder to run python in java, but java cannot display the python result.

python code:

def cal():
    a=4
    b=90
    c=a+b
    return c


if __name__ == "__main__":
    c=cal()
    print c
    print "hello"
    print "hello..................."  

java code

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

public class qqqqqqqqqqqqqqqq {

    public static void main (String args[]) throws IOException {




        try
        {
//      ProcessBuilder pb = new ProcessBuilder("C:/Python27/python","C://Users//admin//Destop//dsf.py" );       
//      Process p = pb.start();

            Runtime r=Runtime.getRuntime();
            Process p=r.exec("cmd /c C:/Python27/python C://Users//admin//Destop//dsf.py");



            BufferedReader bfr = new BufferedReader(new InputStreamReader(p.getInputStream()));

            System.out.println(".........start   process.........");
            String line = "";
            while ((line = bfr.readLine()) != null)
                {
                    System.out.println("Python Output: " + line);
                }
            System.out.println("........end   process.......");

        } catch (Exception e)
        {
            System.out.println(e);
        }



 }
}

java output result:

.........start   process.........
........end   process.......

there is no error with the path and code, Why java cannot run the python ?

1

There are 1 best solutions below

0
teja garapati On

Your code is absolutely correct. Below are some of the corrections needed to run the python code in standard java program.

Use double slashes in providing python exe in Process p=r.exec("cmd /c C:/Python27/python C://Users//admin//Destop//dsf.py");

public class Test {

public static void main (String args[]) throws IOException {

    try
    {
        Runtime r=Runtime.getRuntime();
        Process p=r.exec("cmd /c C:\\Python34\\python.exe D:\\PythonScripts\\HelloWorld.py");

        BufferedReader bfr = new BufferedReader(new InputStreamReader(p.getInputStream()));

        System.out.println(".........start   process.........");
        String line = "";
        while ((line = bfr.readLine()) != null)
            {
                System.out.println("Python Output: " + line);
            }
        System.out.println("........end   process.......");

    } catch (Exception e)
    {
        System.out.println(e);
    }
   }
   }