2017-08-14 54 views
0

我想要及時讀取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(); 
    } 

} 
+0

如果你一次收到結果,那麼一切正常。如果你希望它接收來自外部程序的異步消息,那麼你將需要更多的線程工作,你可能會想要閱讀關於processbuilder – Pfeiffer

+0

爲了幫助你進一步,請嘗試閱讀: 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

回答

3

我寧願ProcessBuilderinheritIO,像

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(); 
} 

對於當前解決方案的工作,你需要處理IO非阻塞線程。

+0

這不回答OP問題,它只是添加你的意見。 (但我同意ProcessBuilder) – Pfeiffer

+0

@Pfeiffer *對於當前的解決方案,您需要在非阻塞線程中處理IO。*請注意,OP當前正在按順序處理IO(並在一個線程中)。 –

+0

對不起,我很困,並沒有讀那條線。 – Pfeiffer