2017-08-14 24 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