将 Python 控制台输出保存到 Java 变量

Save Python console output to Java variable

我在将 python 脚本的输出保存到 java 变量时遇到问题。我的代码看起来像...

Python 脚本:

def main(argv):

    filepath = argv[1]
    ...
    output = results.get_forecast(14).predicted_mean.to_json()
    print(output)
    
    
if __name__ == "__main__":
    main(sys.argv)

它有效 - 结果打印到控制台 - 一切正常。

我的Java代码:

ProcessBuilder pb = new ProcessBuilder("python", "-u",
                "path/to/script.py", args_filepath).inheritIO();

        try {
            Process p = pb.start();

            BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
            StringBuilder predictionString = new StringBuilder();
            String line;

            while((line = br.readLine()) != null) {
                predictionString.append(line);
            }

            int exitCode = p.waitFor();
            System.out.println("VALUE: " + predictionString.toString());
            br.close();

        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }

那部分也有效...我的意思是它的工作方式是执行 python 的代码,将输出写入控制台,但不会将输出字符串保存到 predictionString.

使用redirectErrorStream方法捕获output流。

ProcessBuilder pb = new ProcessBuilder("python", "-u",
                    "path/to/script.py", args_filepath)
                    .redirectErrorStream(true);

而不是

ProcessBuilder pb = new ProcessBuilder("python", "-u",
                "path/to/script.py", args_filepath).inheritIO();