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

Get stdInput from a java Process before the process terminates

所以我正在尝试 运行 一个 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();