我有以下python腳本從蟒蛇命令捕獲輸出,因爲它發生
#!/usr/bin/env python
import subprocess
import sys
from time import sleep
p = subprocess.Popen(["ls", "-l", "."], stdout=subprocess.PIPE)
output, err = p.communicate()
print "*** Running ls -l command ***\n", output
print "I'm gonna wait 1 second"
sleep(1)
print "Waited..."
sleep(5)
print "Finished"
以及執行腳本以下Java程序:
protected List<String> runOutputLinesCommand(String scriptsPath) {
List<String> ret = new ArrayList<String>();
// constructs the python command to be executed
String cmd = scriptsPath
+ COMMAND;
ProcessBuilder pb = new ProcessBuilder(cmd);
pb.redirectErrorStream(true);
try {
// executes the command and waits for its interruption
Process p = pb.start();
String s;
// read from the process's combined stdout & stderr
BufferedReader stdout = new BufferedReader(new InputStreamReader(
p.getInputStream()));
while ((s = stdout.readLine()) != null) {
// appends the output of the command to the ret variable
ret.add(s.trim());
}
p.waitFor();
p.getInputStream().close();
p.getOutputStream().close();
p.getErrorStream().close();
} catch (InterruptedException ex) {
ret.add("script interrupted: " + ex);
} catch (IOException ex) {
ret.add("IOException: " + ex);
ex.printStackTrace(System.out);
} catch (Exception ex) {
ret.add("Exception: " + ex);
ex.printStackTrace(System.out);
}
return ret;
}
我想要的是java程序打印python行正在執行,而不是在所有腳本執行之前。我希望Java程序在發生時打印python腳本的輸出。我怎樣才能在java中實現這一點?