我在我的 java 应用程序中启动了一个 python 脚本
Process p = Runtime.getRuntime().exec("python script.py");
该脚本循环运行,并且仅由事件(或用户交互)取消。该脚本在每个循环周期写入输出,一些文本如“12:22:35 -- Heartbeat”
while True:
print("Heartbeat")
time.sleep(1)
在我的 Java 应用程序中,我想读取出现的输出。我的问题是,如果我使用 BufferReader,它将等到该过程完成,然后读取输出。我是这样读的:
BufferedReader is = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
while ((line = is.readLine()) != null)
System.out.println(line);
如何“实时”读取输出?
为了更好地理解:python 脚本监听硬件按钮,按下该按钮时,会写出一些输出。在我的 java 应用程序中,我想显示此消息并将其发送给一些客户端。
Using https://github.com/zeroturnaround/zt-exec https://github.com/zeroturnaround/zt-exec
new ProcessExecutor().command("python", "script.py")
.redirectOutput(new LogOutputStream() {
@Override
protected void processLine(String line) {
...
}
})
.execute();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)