Flush stdin

Marko Rauhamaa marko at pacujo.net
Wed Oct 22 17:28:43 CEST 2014


random832 at fastmail.us:

> Yes, and 90% of the time, when someone says they want to "flush
> stdin", what they really want to do is go to the next line after
> they've sloppily read part of the line they're on (and the behavior
> they are seeing that they object to is that their next read function
> reads the rest of the current line). The appropriate course of action
> in these cases is to actually read to the next newline and discard the
> data, not to do any kind of flush.

I'm not sure I have seen that. However, somewhat analogously, there are
linux text utilities that read a number of lines and leave the input
intact. Since you can't really effectively read lines, the utilities
routinely read past the designated endpoint and then seek back to the
end of the line.

For example, consider this script:

    seq 20000 >test.dat
    {
         head -n 5 >/dev/null
         head -n 5
    } <test.dat

which outputs:

    6
    7
    8
    9
    10

However, if I modify the script slightly:

    seq 20000 | {
         head -n 5 >/dev/null
         head -n 5
    }

I get:


    1861
    1862
    1863
    1864

because you can't seek back a pipe. The first "head" command has
greedily read in the first 1860 lines and the second one continues where
the first one left off.


Marko



More information about the Python-list mailing list