将python控制台输出保存到java变量

lg40wkob  于 2021-06-29  发布在  Java
关注(0)|答案(1)|浏览(409)

我无法将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 .

nwlls2ji

nwlls2ji1#

使用 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();

相关问题