1

I have problem with saving python script's output to java variable. My code looks like...

Python script:

def main(argv):

    filepath = argv[1]
    ...
    output = results.get_forecast(14).predicted_mean.to_json()
    print(output)
    
    
if __name__ == "__main__":
    main(sys.argv)

And it works - results are printed to console - everything's fine.

My Java code:

ProcessBuilder pb = new ProcessBuilder("python", "-u",
                "path/to/script.py", args_filepath).inheritIO();

        try {
            Process p = pb.start();

            BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
            StringBuilder predictionString = new StringBuilder();
            String line;

            while((line = br.readLine()) != null) {
                predictionString.append(line);
            }

            int exitCode = p.waitFor();
            System.out.println("VALUE: " + predictionString.toString());
            br.close();

        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }

That part also works... I mean it works in a way that it executes the python's code, writes output to console, but it doesn't save the output string to the predictionString.

1
  • What do you believe inheritIO() does, and why do you believe that? --- What do you believe p.getInputStream() does when I/O is inherited, any why do you believe that? Hint: "If the standard output of the subprocess has been redirected using ProcessBuilder.redirectOutput then this method will return a null input stream." Commented Dec 28, 2020 at 17:19

1 Answer 1

2

Use redirectErrorStream method to capturing output stream.

ProcessBuilder pb = new ProcessBuilder("python", "-u",
                    "path/to/script.py", args_filepath)
                    .redirectErrorStream(true);

instead of

ProcessBuilder pb = new ProcessBuilder("python", "-u",
                "path/to/script.py", args_filepath).inheritIO();
Sign up to request clarification or add additional context in comments.

1 Comment

wow - it works, thank you so much! need to read more about that

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.