2

So I am trying to run a python script and want to obtain the stdInput from the script so I can use it. I have noticed the stdInput will hang until the process has finished.

Python script:

import time
counter = 1
while True:
    print(f'{counter} hello')
    counter += 1
    time.sleep(1)

Java code:

public class Main {

    public static void main(String[] args) throws IOException {
        Runtime rt = Runtime.getRuntime();
        String[] commands = {"python3", "/Users/nathanevans/Desktop/Education/Computing/Programming/Java/getting script output/src/python/main.py"};
        Process proc = rt.exec(commands);

        BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream()));
        BufferedReader stdError = new BufferedReader(new InputStreamReader(proc.getErrorStream()));

        System.out.println("stdOuput of the command");
        String s = null;
        while ((s = stdInput.readLine()) != null) {
            System.out.println(s);
        }

        System.out.println("stdError of the command");
        while ((s = stdError.readLine()) != null) {
            System.out.println(s);
        }
    }
}

Nothing is printed from the java application until the Process is terminated but in this case when I terminate the java application.

How would I obtain the stdInput as it is written by the script?

xKean
  • 94
  • 6

1 Answers1

0

In order to get Python output immediately you'd need to turn off Python output buffering - that is covered here

This may fix your problem but you may run into second issue because you are reading STD IN / OUT in one thread. If STDERR buffer fills before you read to end of STDIN it will block the process. The solution then is to read STD/IN/ERR in separate threads or use ProcessBuilder which allows redirect to files or redirect STDERR to STDOUT:

ProcessBuilder pb = new ProcessBuilder(commands);
    pb.redirectOutput(outfile);
    pb.redirectError(errfile);
//or
    pb.redirectErrorStream(true);
Process p = pb.start();
DuncG
  • 12,137
  • 2
  • 21
  • 33