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
Solution 1:
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
defmain33():
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)
publicstaticvoidmain(String[] args)throws Exception {
StringfilePath="D:\\test\\test.py";
ProcessBuilderpb=newProcessBuilder()
.command("python", "-u", filePath, "main33");
Processp= pb.start();
BufferedReaderin=newBufferedReader(
newInputStreamReader(p.getInputStream()));
StringBuilderbuffer=newStringBuilder();
Stringline=null;
while ((line = in.readLine()) != null){
buffer.append(line);
}
intexitCode= p.waitFor();
System.out.println("Value is: "+buffer.toString());
System.out.println("Process exit value:"+exitCode);
in.close();
}
Solution 2:
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);
Post a Comment for "How To Return Value From Python Script To Java Using Processbuilder?"