0

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?

asked Mar 14, 2016 at 6:33
1

1 Answer 1

2

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);
 }
answered Mar 14, 2016 at 7:59
Sign up to request clarification or add additional context in comments.

2 Comments

Hey can you guide me on how to do this on Linux?
you can use String[] commands = new String[]{"/bin/sh", "-c", command}; ProcessBuilder builder = new ProcessBuilder(commands ); if in the case of debian you can try "/bin/bash" instead of "/bin/sh"

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.