Surras Surras - 1 year ago 106
Java Question

Read live output of process in java

I start a python script in my java application with

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


This script runs in a loop and is only canceled by an event (or user interaction). The script writes to the output every loop cycle, some text like "12:22:35 -- Heartbeat"

while True:
print("Heartbeat")
time.sleep(1)


In my Java application I want to read this output as it appears. My problem is, if I use the BufferReader, it will wait until the process is completed and after that it reads the output. Here is how I read it:

BufferedReader is = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;

while ((line = is.readLine()) != null)
System.out.println(line);


How can I read the output "live"?

For better understanding: the python-script listen on a hardware button, and when this button is pressed, some output is written out. And in my java application I want to show up this message and sent it to some clients.

Answer Source

Using https://github.com/zeroturnaround/zt-exec

new ProcessExecutor().command("python", "script.py")
    .redirectOutput(new LogOutputStream() {
        @Override
        protected void processLine(String line) {
            ...
        }
    })
    .execute();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download