2

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

4
  • "I would really appreciate any advice" - don't call a Python script from a Java program? Commented Feb 4, 2016 at 23:05
  • Why not use Jython? Commented Feb 4, 2016 at 23:11
  • PS py4j is a great way to get python and java communicating (rather than just calling scripts) py4j.org Commented Feb 4, 2016 at 23:12
  • I was just playing around with the processbuilder, the python - Script was just a little program to experiment with, so I can understand how it works. Commented Feb 5, 2016 at 13:33

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your suggestion, but sadly it still won't work. I tried to modify the Java-Program to access a .jar File instead of a Python-Script but the same error occurs, so it's probably an mistake in the Java-Program not in the Python-Script.

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.