-->

PumpStreamHandler can capture the process output i

2019-08-21 08:59发布

问题:

I try to capture a python process output via apache-commons-exec. But it looks like it won't print the output, the output is only displayed after I the python process is finished.

Here's my java code

CommandLine cmd = CommandLine.parse("/Users/jzhang/anaconda/bin/python");
cmd.addArgument("/Users/jzhang/a.py");
DefaultExecutor executor = new DefaultExecutor();
ExecuteWatchdog watchDog = new ExecuteWatchdog(ExecuteWatchdog.INFINITE_TIMEOUT);
executor.setWatchdog(watchDog);

executor.execute(cmd);

And this is the python code I want to execute (I only get the output after the python process is exited, but what I want is to get the output in real time)

for i in range(1,10):
  print(i)

import time

time.sleep(10)

回答1:

I find the answner, I should use set flush to true. E.g.

print('hello world', flush=True)