Flush stdin

Tim Chase python.list at tim.thechases.com
Sat Oct 18 13:32:07 EDT 2014


On 2014-10-18 17:55, Nobody wrote:
> On Fri, 17 Oct 2014 12:38:54 +0100, Empty Account wrote:
> 
> > I am using netcat to listen to a port and python to read stdin
> > and print to the console.
> > 
> > nc -l 2003 | python print_metrics.py
> > 
> > sys.stdin.flush() doesn’t seem to flush stdin,
> 
> You can't "flush" an input stream.

You can't flush it, but you can make it unbuffered.  You can either
force python to use unbuffered stdio:

  python -u myfile.py

or you can get an unbuffered handle to the file

 import os, sys
 buffer_size = 1
 new_stdin = os.fdopen(sys.stdin.fileno(), 'r', buffer_size)
 for c in new_stdin:
   do_something(c)

though based on my reading, the first method works with both Py2
and Py3k while the second method doesn't reliably work in Py3k.

-tkc







More information about the Python-list mailing list