[Tutor] communication between java and python?

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Fri Jan 14 07:38:09 CET 2005

On Thu, 13 Jan 2005, joeri honnef wrote:

> I'm trying to communicate between Python and Java and using os.popen().
> But thing dont work...The Java program reads strings from stdin and the
> python program just writes to stdout.

Hi Joeri,

You may want to look at:


which explains some of the tricky flow-control issues that can happen
during inter-process communication.  As far as I can tell, the Java code
that you have to read a character from standard input:

    // return EOF if end of file or IO error
    private static void readC() {
        try { c = System.in.read(); }
        catch(IOException e) { c = EOF; }

has the possibility of blocking if the input stream has not been closed.

Other folks have already commented that, in the interaction that you're
doing with the program:

> handlers = os.popen('java StdIn)
> handlers[0].write('string')
> return_value_from_java = handlers[1].read()

your program needs to use something like popen2 to get separate input and
output files.  But the program also needs to be aware to close the
streams, or else risk the potential of deadlocking.

If it helps to see why, imagine that we modify:

> handlers[0].write('string')
> return_value_from_java = handlers[1].read()

to something like:


We can call write() several times, and as far as the Java process knows,
it might need to expect more input.  That's why closing the input stream
is necessary, to signal to the Java program, through EOF, that there's no
more characters to read.

If you have more questions, please feel free to ask!

More information about the Tutor mailing list