0

I would like to call Python code from Java. What would be the best way of achieving that, so I could:

  • Start specific function or script with parameters passed from Java
  • Make communication asynchronous (I don't want to block user interface written in Java and I would like to send objects and arguments between Java and Python threads)

The goal of such application would be to create GUI written in Java, which allows user to perform tasks written in Python and receive additional output in between while Python is doing some work.

4
  • Socket communication is code language independent, so what have you tried? Commented Feb 27, 2017 at 19:58
  • Yeah :) I thought of server solution, but I was wondering if maybe there's a more JNI-like one (like I could for example make callbacks from C to Java via JNI) Commented Feb 27, 2017 at 20:05
  • Have you looked at Jython? jython.org/jythonbook/en/1.0/… may give you somewhere to start. Commented Feb 27, 2017 at 20:05
  • Thanks! I'll look it up :) Commented Feb 27, 2017 at 20:09

1 Answer 1

1

Since you want to call Python program asynchronously why not take advantage of Java's multithreading? Basically the idea is you call Python code in the separate thread. In the simplest (Java 8) form this will be something like:

new Thread(() -> {
    ProcessBuilder pb = new ProcessBuilder("python","mytest.py", param1, param2);
    Process p = pb.start();
    // more code to capture the output here
}).start();

Or you can use something bit more sophisticated like java.util.concurrent.FutureTask but idea is still the same, your main program spawns the thread and goes its merry way without waiting

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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.