Search code examples
javapythonprocessbuilder

Java Processbuilder Stream to Python-Script


I have a minor Problem with a small Project I'm trying to do. I'm trying to use a Java-Program to call a Python-Script.

Java:

ProcessBuilder pb = new ProcessBuilder("python3", "tmp.py");
process = pb.start();

OutputStream stdin = process.getOutputStream();
InputStream stderr = process.getErrorStream();
InputStream stdout = process.getInputStream();

BufferedReader reader = new BufferedReader(new InputStreamReader(stdout));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(stdin));

writer.write("example" + "\n");

String output = reader.readLine();

Python-Script tmp.py (example):

import sys

sys.stdin.readline()
print("Hello World")

It wont terminate, seemingly because sys.sdin.readline() isnt catching any input and if I remove this line it terminates just fine. (stderror was empty too) I tried different things to fix this but nothing seems to work.

I would really appreciate any advice. Thanks in advance.

(Update: I tried to modify the Java-Program to access a .jar File instead of a Python-Script but the same error occurs here to. Using the Python Method subprocess.Popen() to access the Script however works just fine.)


Solution

  • Make sure you start python unbuffered with -u flag:

    Force the binary layer of the stdout and stderr streams (which is available as their buffer attribute) to be unbuffered. The text I/O layer will still be line-buffered if writing to the console, or block-buffered if redirected to a non-interactive file.

    Edit

    I recommend reviewing the buffering all the same. The python unbuffered is a common one, but you possibly still have some buffering. Make sure you flush java writer, writer.flush().