在进程终止之前从Java进程获取stdInput

问题描述

因此,我尝试运行python脚本,并希望从脚本中获取stdInput,以便可以使用它。我注意到stdInput将挂起,直到该过程完成。

Python脚本:

import time
counter = 1
while True:
    print(f'{counter} hello')
    counter += 1
    time.sleep(1)

Java代码

public class Main {

    public static void main(String[] args) throws IOException {
        Runtime rt = Runtime.getRuntime();
        String[] commands = {"python3","/Users/nathanevans/Desktop/Education/Computing/Programming/Java/getting script output/src/python/main.py"};
        Process proc = rt.exec(commands);

        BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream()));
        BufferedReader stdError = new BufferedReader(new InputStreamReader(proc.getErrorStream()));

        System.out.println("stdOuput of the command");
        String s = null;
        while ((s = stdInput.readLine()) != null) {
            System.out.println(s);
        }

        System.out.println("stdError of the command");
        while ((s = stdError.readLine()) != null) {
            System.out.println(s);
        }
    }
}

在进程终止之前,Java应用程序不会打印任何内容,但是在这种情况下,当我终止Java应用程序时。

我如何获取脚本编写的stdInput

解决方法

为了立即获取Python输出,您需要关闭Python输出缓冲-这已here

这可能会解决您的问题,但由于在一个线程中读取STD IN / OUT,您可能会遇到第二个问题。如果在读到STDIN的末尾之前STDERR缓冲区已满,它将阻塞该过程。然后,解决方案是在单独的线程中读取STD / IN / ERR或使用ProcessBuilder,该程序允许重定向到文件或将STDERR重定向到STDOUT:

ProcessBuilder pb = new ProcessBuilder(commands);
    pb.redirectOutput(outfile);
    pb.redirectError(errfile);
//or
    pb.redirectErrorStream(true);
Process p = pb.start();