I've searched and only found examples where we output the output after
the system command has finished, rather than during its execution.
这很奇怪,因为您的示例应该在执行命令时转储输出。在
您可以尝试直接从InputStream读取,而不是使用BufferedReader,因为在进程退出之前,readLine所需的条件可能无法满足。在
我还建议您直接使用ProcessBuilderover Process,因为除了其他任何东西,它允许您将输出从错误流重定向到输入流,允许您只读取一个流而不是两个。。。在
这也可能是Python的问题,以及它如何刷新输出缓冲区。。。在
例如,与其等待BufferedReader决定何时返回,不如在流发生/被报告时打印流中的每个字符ProcessBuilder pb = new ProcessBuilder("test.py");
pb.redirectError();
Process p = pb.start();
InputStream is = null;
try {
is = p.getInputStream();
int in = -1;
while ((in = is.read()) != -1) {
System.out.print((char)in);
}
} finally {
try {
is.close();
} catch (Exception e) {
}
}
更新
在进行一点阅读之后,Python似乎在将其发送到stdout之前将其缓冲出来。我不认为您可以在Java端解决这个问题,但是需要改变Python的运行方式或脚本的工作方式。在