Run python script in java using ProcessBuilder

Run python script in java using ProcessBuilder

Hey guy’s, 

In this blog we are going to discuss the easiest steps to execute python script in Java and read the output of script.

Following are steps below,

Suppose we wanted to read output from python code inside out Java code,

Step1 : – First you must have Python install in our system so that you can play with this example.

Step2 : – For Example, suppose our python code is,

Script.py

import sys
a = 5
b = 6
c = a + b
sum = "sum of two number is :- "
print("-----------------",sum,"-------------------")
print(c)

Step3 : – Here, we will write java code in ReadPython file to read output from python script. See the below code,

ReadPython.java

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class ReadPython {
public static void main(String[] args) throws IOException, InterruptedException {
String path = "C:\Users\Admin\Desktop\pythoncodetest/script.py";
ProcessBuilder pb = new ProcessBuilder("python","C:\Users\Admin\Desktop\pythoncodetest/script.py").inheritIO();
Process p = pb.start();
p.waitFor();
BufferedReader bfr = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
while ((line = bfr.readLine()) != null) {
System.out.println(line);
}
}
}

Step4 : – Run java code now to see the output in console.

For example,

Thanks….

If you have any doubt then let us know in comment box.