我想要及时读取execute python脚本的输出,但是当我这样做时,java总是等待python直到完成(5秒后)所有进程。Java程序显示来自Python的连续输出
我转载我的问题如下:
read.java
public static void main(String[] args) throws IOException{
Runtime rt = Runtime.getRuntime();
String[] commands = {"python.exe","hello.py"}; //execute the hello.py under path
Process proc = rt.exec(commands);
BufferedReader stdInput = new BufferedReader(new
InputStreamReader(proc.getInputStream()));
BufferedReader stdError = new BufferedReader(new
InputStreamReader(proc.getErrorStream()));
// read the output from the command
System.out.println("Here is the standard output of the command:\n");
String s = null;
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
}
// read any errors from the attempted command
System.out.println("Here is the standard error of the command (if any):\n");
while ((s = stdError.readLine()) != null) {
System.out.println(s);
}
hello.py
import time
print "123\n"
time.sleep(5) #wait 5 sec and print next line
print '456'
---更新---
我重写我的代码如下所示,但它似乎不起作用。
public class Hello implements Runnable {
public void run() {
String[] commands = { "python.exe", "hello.py" };
ProcessBuilder pb = new ProcessBuilder(commands);
pb.inheritIO();
try {
Process p = pb.start();
int result = p.waitFor();
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String args[]) {
(new Thread(new Hello())).start();
}
}
如果你一次收到结果,那么一切正常。如果你希望它接收来自外部程序的异步消息,那么你将需要更多的线程工作,你可能会想要阅读关于processbuilder – Pfeiffer
为了帮助你进一步,请尝试阅读: http://www.javaworld。 com/article/2071275/core-java/when-runtime-exec --- won-t.html?page = 2 https://www.java-tips.org/java-se-tips-100019/88888889 -java-util/426-from-runtimeexec-to-processbuilder.html – Pfeiffer