I am trying to understand Jython. I have some algorithms written in Python that I want to integrate in Java. The Jython docs are very complex for me to understand. All I could get from them is that I can run individual Python statements from Java by embedding them like this:
interp = new PythonInterpreter();
interp.exec("import sys");
interp.exec("print sys");
But I can't embed my giant algorithms like that. I need to run the py scripts. Is there any way to do that? Can I get a hello world example where the print("hello") statement is written in a py script file and the output is shown on a Java console?
1 Answer 1
Jython its the better option
else you can run python program from the java using the command prompt and collect the output back in java
as eg:
ProcessBuilder builder = new ProcessBuilder(
"cmd.exe", "/c", "C:\\Python27\\python.exe C:\\Users\\Bens\\Desktop\\test.py");
builder.redirectErrorStream(true);
Process p = builder.start();
BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
while (true) {
line = r.readLine();
if (line == null) {
break;
}
System.out.println(line);
}
} catch (IOException ex) {
Logger.getLogger(TCPServer.class.getName()).log(Level.SEVERE, null, ex);
}
PythonInterpreter.execfile()? See jython.org/javadoc/org/python/util/….