'How can i execute a python script using java?
I'm trying to integrate a python script in java. I want my java program to be able to execute my python script
I tried to code a class named PythonCaller made to execute a test python script
package pythontest;
import java.io.*;
public class PythonCaller {
public static void main(String[] args) throws IOException{
// TODO Auto-generated method stub
// set up the command and parameter
String pythonScriptPath = "D:\\Programmes\\test.py";
String[] cmd = new String[2];
cmd[0] = "D:\\Programmes\\python.exe"; // check version of installed python: python -V
cmd[1] = pythonScriptPath;
// create runtime to execute external command
Process pr = Runtime.getRuntime().exec("python D:/Documents/Télécom/Programmation/workspace python/test.py");
System.out.println("adhi");
// retrieve output from python script
BufferedReader bfr = new BufferedReader(new InputStreamReader(pr.getInputStream()));
System.out.println(bfr.readLine());
String line = "";
try {
while((line = bfr.readLine()) != null) {
// display each output line form python script
System.out.println(line);
System.out.println("daiuh");
}
}
catch(IOException e) {
System.out.println("Exception in reading output" + e.toString());
}
}
}
When i execute it, it appears that bfr.readLine() returns null
Here is the script in test.py :
print("aiujadh")
print("f")
what i dont understand is that i did tests with the exact same code before, and it worked. I changed it because it failed to read the lines that were not "prints". Then i moved back to the working code, and it doesnt work anymore. I looked at similar topics on the internet, and i do not understand why my code doesn't work. Can somebody try to explain me pls ?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
