Running a .py file from Java

You can use like this also:

String command = "python /c start python path\to\script\script.py";
Process p = Runtime.getRuntime().exec(command + param );

or

String prg = "import sys";
BufferedWriter out = new BufferedWriter(new FileWriter("path/a.py"));
out.write(prg);
out.close();
Process p = Runtime.getRuntime().exec("python path/a.py");
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
String ret = in.readLine();
System.out.println("value is : "+ret);

Run Python script from Java


You can run the python script

Process p = Runtime.getRuntime().exec(PYTHON_ABSOLUTE_PATH, script_path)

To get the PYTHON_ABSOLUTE_PATH just type

which python2.7

in terminal


I believe we can use ProcessBuilder

Runtime.getRuntime().exec("python "+cmd + py + ".py");
.....
//since exec has its own process we can use that
ProcessBuilder builder = new ProcessBuilder("python", py + ".py");
builder.directory(new File(cmd));
builder.redirectError();
....
Process newProcess = builder.start();

String command = "cmd /c python <command to execute or script to run>";
    Process p = Runtime.getRuntime().exec(command);
    p.waitFor();
    BufferedReader bri = new BufferedReader(new InputStreamReader(p.getInputStream()));
    BufferedReader bre = new BufferedReader(new InputStreamReader(p.getErrorStream()));
          String line;
        while ((line = bri.readLine()) != null) {
            System.out.println(line);
          }
          bri.close();
          while ((line = bre.readLine()) != null) {
            System.out.println(line);
          }
          bre.close();
          p.waitFor();
          System.out.println("Done.");

    p.destroy();

Tags:

Python

Java