简体   繁体   中英

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. I am expecting the value "This is what I am looking for" in 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.

test.py code

import sys

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


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

Java code

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. In case you need to send something back to Java process you need to write that to print().

Modified both of your python and java code snippets.

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 . 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM