Does fileinput.input() read STDIN all at once?

Jonathan Gardner jgardner.jonathangardner.net at gmail.com
Tue Dec 18 14:24:05 EST 2007


On Dec 18, 5:55 am, Adam Funk <a24... at ducksburg.com> wrote:
> I'm using this sort of standard thing:
>
>    for line in fileinput.input():
>       do_stuff(line)
>
> and wondering whether it reads until it hits an EOF and then passes
> lines (one at a time) into the variable line.  This appears to be the
> behaviour when it's reading STDIN interactively (i.e. from the
> keyboard).
>
> As a test, I tried this:
>
>    for line in fileinput.input():
>       print '**', line
>
> and found that it would print nothing until I hit Ctl-D, then print
> all the lines, then wait for another Ctl-D, and so on (until I pressed
> Ctl-D twice in succession to end the loop).
>

There is probably a 1024 byte buffer. Try filling it up and see if you
get something before you hit CTRL-D.

Otherwise, the writers have to flush the buffer if they want a line to
be sent before the buffer fills up. C++ endl would do this, I believe,
in addition to printing '\n'.

Note that terminals (what you get if you are typing from the command
line) are terminals and behave quite differently than open files.

> Is it possible to configure this to pass each line of input into line
> as it comes?
>

It's up to the writer to flush the buffers. There's not much you can
do, so just learn to live with it.

It sounds like you want to write some kind of interactive program for
the terminal. Do yourself a favor and use curses or go with a full-
blown GUI.



More information about the Python-list mailing list