Silly question re: 'for i in sys.stdin'?

Steven Bethard steven.bethard at gmail.com
Sun Apr 3 23:49:42 EDT 2005


Jeff Epler wrote:
> The iterator for files is a little bit like this generator function:
>     def lines(f):
>         while 1:
>             chunk = f.readlines(sizehint)
>             for line in chunk: yield line
> Inside file.readlines, the read from the tty will block until sizehint
> bytes have been read or EOF is seen.

I'm not the OP, but thanks for putting 2 and 2 together for me anyway. 
:)  I just tested it on my Windows XP box, and discovered that
     for line in sys.stdin:
         ...
actually does read a line at a time, as long as the lines are at least 
8192 characters long. ;)

>     def lines(f):  # untested
>         """lines(f)
> If f is a terminal, then return an iterator that gives a value after
> each line is entered.  Otherwise, return the efficient iterator for
> files."""
>         if hasattr(f, "fileno") and isatty(f.fileno()):
>             return iter(f.readline, '')
>         return iter(f)

Slick.  Thanks!

STeVe



More information about the Python-list mailing list