How to read from Process.getInputStream asynchronously during the invoked process excution
Question: I have a java program which need to start a python process and get response
from that.

what I want is to get response immediately when python print something. I'm
not asking for current java thread not block. but reading from the inputStream
asynchronously.

I use java 7's
[Process](http://docs.oracle.com/javase/7/docs/api/java/lang/Process.html)
class to start a python process.

My relating java code:

    
    
    List<String> args = java.util.Arrays.asList("python", "test.py");
    ProcessBuilder pb = new ProcessBuilder(args);
    pb.directory(new File("/dir/to/python/script"));
    Process p = processBuilder.start();
    
    BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
    
    String ret1 = in.readLine();
    System.out.println("ret1 is: " + ret1);
    
    String ret2 = in.readLine();
    System.out.println("ret2 is: " + ret2);
    

My python script test.py is :

    
    
    import time
    
    if __name__ == '__main__':
        print("start signal")
    
        time.sleep(10)
        print("end signal")
    

I run the java code, in the console, nothing printed, but after 10 seconds,
"start signal" and "end signal" both appeared at the same time.

It seemed that the readLine() will block until the whole python process return
and terminate.

Can't this method read response when python still running?

What I want is that the java code blocked when it reached the readLine(), And
when python print something, java read it through readLine, and then go on
executing until meet the second readLine() wait for python to print.

How Can I achieve that purpose?

    
    
    _______eidit________
    

I also tried using a thread to read from the inputStream. I think the only
purpose of using thread is just not making readLine() to block the current
thread. But I don't care that, I want readLine() to read from python output
immediately not when python terminated.

I googled a lot and I noticed that somebody mentioned that this:

    
    
    Maybe the output is being buffered because the command knows 
    it is writing to a pipe rather than a terminal?
    

but I can't get more information about that.

Can Somebody explain this? thank you for reading so long!


Answer: OK, I got the problem is not because of the java code, but the python code.

I need to set

    
    
    sys.stdout.flush()
    

after every print statement. So the BufferdReader in java can read every
single print immediately.

