问题描述
我使用
Process p = Runtime.getRuntime().exec("python script.py");
此脚本循环运行,仅被事件(或用户交互)取消.脚本在每个循环周期写入输出,一些文本如12:22:35 -- Heartbeat"
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)
在我的 Java 应用程序中,我想读取出现的输出.我的问题是,如果我使用 BufferReader,它会等到进程完成,然后读取输出.我是这样读的:
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);
如何读取实时"输出?
为了更好地理解:python-script 监听硬件按钮,当按下这个按钮时,会写出一些输出.在我的 Java 应用程序中,我想显示此消息并将其发送给某些客户端.
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.
推荐答案
使用 https://github.com/zeroturnaround/zt-exec
new ProcessExecutor().command("python", "script.py")
.redirectOutput(new LogOutputStream() {
@Override
protected void processLine(String line) {
...
}
})
.execute();
这篇关于在java中读取进程的实时输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!