如何使用 ProcessBuilder 将值从 Python 脚本返回到 Java?

我正在尝试使用ProcessBuilder将python脚本的返回值获取到Java中。我期望在Java中具有“这就是我正在寻找的”的值。谁能告诉我下面的逻辑中有什么问题?


我正在使用python3,并希望使用java标准库来完成此操作。


test.py 代码


import sys


def main33():

    return "This is what I am looking for"



if __name__ == '__main__':

    globals()[sys.argv[1]]()

Java 代码


String filePath = "D:\\test\\test.py";


ProcessBuilder pb = new ProcessBuilder().inheritIO().command("python", "-u", filePath, "main33");


Process p = pb.start();

int exitCode = p.waitFor();


BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));

String line = "";


line = in.readLine();

while ((line = in.readLine()) != null){

    line = line + line;

}


System.out.println("Process exit value:"+exitCode);

System.out.println("value is : "+line);

in.close();

输出


Process exit value:0

value is : null


SMILET
浏览 203回答 2
2回答

守候你守候我

当您从另一个进程生成一个进程时,它们只能(主要是)通过其输入和输出流进行通信。因此,你不能期望 python 中 main33() 的返回值到达 Java,它将仅在 Python 运行时环境中结束其生命周期。如果你需要把一些东西发回Java进程,你需要把它写到print()。修改了 python 和 java 代码片段。import sysdef main33():    print("This is what I am looking for")if __name__ == '__main__':    globals()[sys.argv[1]]()    #should be 0 for successful exit    #however just to demostrate that this value will reach Java in exit code    sys.exit(220)public static void main(String[] args) throws Exception {               String filePath = "D:\\test\\test.py";              ProcessBuilder pb = new ProcessBuilder()            .command("python", "-u", filePath, "main33");                Process p = pb.start();         BufferedReader in = new BufferedReader(            new InputStreamReader(p.getInputStream()));        StringBuilder buffer = new StringBuilder();             String line = null;        while ((line = in.readLine()) != null){                       buffer.append(line);        }        int exitCode = p.waitFor();        System.out.println("Value is: "+buffer.toString());                        System.out.println("Process exit value:"+exitCode);                in.close();    }

守着一只汪

您过度使用了变量 。它不能既是当前的输出线,也不能是到目前为止看到的所有线。添加第二个变量以跟踪累积输出。lineString line;StringBuilder output = new StringBuilder();while ((line = in.readLine()) != null) {    output.append(line);          .append('\n');}System.out.println("value is : " + output);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java