Search code examples
javapythonprocessbuilder

Save Python console output to Java variable


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.


Solution

  • 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();