Reading from sys.stdin reads the whole file in

Peter Otten __peter__ at web.de
Wed Aug 27 03:42:40 EDT 2014


Steven D'Aprano wrote:

> I'm trying to read from stdin. Here I simulate a process that slowly
> outputs data to stdout:
> 
> steve at runes:~$ cat out.py
> import time
> 
> print "Hello..."
> time.sleep(10)
> print "World!"
> time.sleep(10)
> print "Goodbye!"

In addition to what already has been said: you can switch off output 
buffering of stdout/stderr with

python -u out.py

or by setting the PYTHONUNBUFFERED environment variable.

You still need the readline trick to get unbuffered input. Quoting the man-
page:

"""

       -u     Force stdin, stdout and stderr to be totally  unbuffered.   On
              systems where it matters, also put stdin, stdout and stderr in
              binary mode.  Note that there is internal buffering in  xread‐
              lines(),  readlines()  and file-object iterators ("for line in
              sys.stdin") which is not influenced by this option.   To  work
              around  this,  you  will  want  to  use "sys.stdin.readline()"
              inside a "while 1:" loop.
"""




More information about the Python-list mailing list