Sur*_*ras 2 python java stdout
我在我的 java 应用程序中启动了一个 python 脚本
Process p = Runtime.getRuntime().exec("python script.py");
Run Code Online (Sandbox Code Playgroud)
该脚本循环运行,仅被事件(或用户交互)取消。该脚本在每个循环周期写入输出,一些文本如“12:22:35 -- Heartbeat”
while True:
print("Heartbeat")
time.sleep(1)
Run Code Online (Sandbox Code Playgroud)
在我的 Java 应用程序中,我想读取出现的输出。我的问题是,如果我使用 BufferReader,它会等到进程完成,然后读取输出。这是我阅读它的方式:
BufferedReader is = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
while ((line = is.readLine()) != null)
System.out.println(line);
Run Code Online (Sandbox Code Playgroud)
如何读取“实时”输出?
为了更好地理解:python 脚本监听硬件按钮,当按下该按钮时,会写出一些输出。在我的 Java 应用程序中,我想显示此消息并将其发送给一些客户端。
小智 5
使用https://github.com/zeroturnaround/zt-exec
new ProcessExecutor().command("python", "script.py")
.redirectOutput(new LogOutputStream() {
@Override
protected void processLine(String line) {
...
}
})
.execute();
Run Code Online (Sandbox Code Playgroud)