2

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

2 Answers 2

9

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();
    }
Sign up to request clarification or add additional context in comments.

3 Comments

This still does not add the output from python to line in Java. line is still null. ouput from python script is printed on console. ** This is what I am looking for Process exit value:220 value is : null**
As when creating ProcessBuilder you have used inheritIO(), the IO of child process is merged with Parent process. Also, your waitFor() call was at incorrect place. I have updated my solution, hope this is what you are looking for.
Thank you for the correction. This works as expected now.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.