我想要及時讀取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