简体   繁体   English

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

[英]How to return value from Python script to Java using ProcessBuilder?

I am trying to get return value from python script into Java using ProcessBuilder. 我试图使用ProcessBuilder从python脚本获取返回值到Java。 I am expecting the value "This is what I am looking for" in Java. 我期待Java中的值“这就是我要找的东西”。 Can anyone point me as to what is wrong in below logic? 任何人都可以指出我在下面的逻辑中有什么问题吗?

I am using python3 and looking to have this done using java standard libraries. 我正在使用python3并希望使用java标准库完成此操作。

test.py code test.py代码

import sys

def main33():
    return "This is what I am looking for"


if __name__ == '__main__':
    globals()[sys.argv[1]]()

Java code 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();

output 产量

Process exit value:0
value is : null

When you spawn a process from another process, they can only (mostly rather) communicate through their input and output streams. 当您从另一个进程生成进程时,它们只能(通常更确切地说)通过其输入和输出流进行通信。 Thus you cannot expect the return value from main33() in python to reach Java, it will end its life within Python runtime environment only. 因此,您不能指望python中main33()的返回值到达Java,它将仅在Python运行时环境中终止它的生命。 In case you need to send something back to Java process you need to write that to print(). 如果您需要将某些内容发送回Java进程,则需要将其写入print()。

Modified both of your python and java code snippets. 修改了你的python和java代码片段。

import sys
def 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();
    }

You're overusing the variable line . 你过度使用变量line It can't be both the current line of output and all the lines seen so far. 它不能同时输出的电流线迄今所看到的所有行。 Add a second variable to keep track of the accumulated output. 添加第二个变量以跟踪累积的输出。

String line;
StringBuilder output = new StringBuilder();

while ((line = in.readLine()) != null) {
    output.append(line);
          .append('\n');
}

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用ProcessBuilder从Java运行并行python脚本 - How to run parallel python scripts from java using the ProcessBuilder 使用processBuilder的Java / python - Java/python using processBuilder Java - 如何使用 processbuilder 调用 python 类 - Java - How to call python classes using processbuilder 使用java ProcessBuilder从批处理文件运行python脚本不起作用 - run python script from batchfile doesn't work by using java ProcessBuilder 使用Processbuilder从Java Web应用程序调用python脚本 - Calling python script from java web application with Processbuilder 使用ProcessBuilder从Java设置Unix脚本中的环境变量 - Setting Environment Variables in Unix Script from Java using ProcessBuilder 从Java调用在Mac使用的ProcessBuilder使Node.js脚本 - Calling a node.js script from java using ProcessBuilder in mac Java ProcessBuilder 无法在 Java 中运行 Python 脚本 - Java ProcessBuilder not able to run Python script in Java 如何使用ProcessBuilder使BufferedReader显示正在运行的python脚本的实时输出? - How can I get BufferedReader to display live outputs from a running python script using ProcessBuilder? Java,带有Python模块(numpy)的Python脚本的ProcessBuilder - Java, ProcessBuilder for python script with python module (numpy)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM