0

So I'm currently working on a project which is using Java for it's GUI and a python script to perform the primary functions of the program.

I was wondering if there is a way to run the python script from within the application directory, and then send its output to the GUI program for parsing. The output could be JSON/YAML/Plaintext etc (so this will be parsed by the GUI).

Two options I thought of (which may or may not work) were:

  1. Running the Python program separately and having it output a file which is then read by the Java program (This is my least favourite)
  2. Using ProcessBuilder or Runtime.exec to run the Python program.. But then how would I get the output?

If neither of my options I thought of are feasible or would work, then is there a way to do this much better?

Thanks!

1
  • 1
    Both would work, but I'd prefer ProcessBuilder#redirectOutput(Redirect) and redirectError. Use separate threads for reading from the stream, otherwise the process may hang after filling its output buffers. Commented Dec 30, 2017 at 23:02

1 Answer 1

1

Runtime.exec gives you an input stream that can be wrapped in a buffered reader to parse the output.

      try {

        Process p = Runtime.getRuntime().exec("python 1.py'");

        BufferedReader stdInput = new BufferedReader(new 
             InputStreamReader(p.getInputStream()));

        BufferedReader stdError = new BufferedReader(new 
             InputStreamReader(p.getErrorStream()));

        // read the output from the command
        System.out.println("Here is the standard output of the command:\n");
        while ((s = stdInput.readLine()) != null) {
            System.out.println(s);
        }

        // read any errors from the attempted command
        System.out.println("Here is the standard error of the command (if any):\n");
        while ((s = stdError.readLine()) != null) {
            System.out.println(s);
        }

        System.exit(0);
    }
    catch (IOException e) {
        System.out.println("exception happened - here's what I know: ");
        e.printStackTrace();
        System.exit(-1);
    }
Sign up to request clarification or add additional context in comments.

1 Comment

Your example is quite unclear. To me it just looks like your reading in a file called write.txt, so it doesn't really answer my question as to whether I can effectively execute the python script to get its output

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.