Java程序显示Python的连续输出

时间:2017-08-14 04:39:11

标签: java python

我想及时读取execute python脚本的输出,但是当我这样做时,java总是等待python直到它完成(5秒后)所有进程。

我将我的问题转载如下:

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

}

1 个答案:

答案 0 :(得分: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。