idiomatic analogue of Perl's: while (<>) { ... }

Cameron Simpson cs at
Fri Sep 2 01:01:59 EDT 2011

On 01Sep2011 22:02, Sahil Tandon <sahil at> wrote:
| [Thanks to everyone who responded]
| Steven D'Aprano wrote:
| >On Thu, 1 Sep 2011 02:56 pm Sahil Tandon wrote:
| >>%%
| >># unbuffer STDOUT
| >>sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)
| >
| >I've never bothered with unbuffered stdout, but that looks fine to me.
| >
| >I'm not sure if it is necessary though, because print seems to automatically
| >flush the buffer after each line in my testing. Unless you're printing
| >repeatedly to the same line, I'm not sure unbuffered stdout is helpful.
| I found it necessary because without reopening sys.stdout with
| buffering explicitly turned off, I would have to manually flush the
| buffer after each print.  This is because the program must reply
| (via writing to STDOUT) after parsing each line read via STDIN.  If
| I neither disable buffering nor manually flush after each print, the
| program just hangs instead of printing right away.

Yes. Steven was probably testing on a terminal. UNIX stdio buffering is
line buffered on a terminal and block buffered otherwise (except for
stderr, which is normally unbuffered regardless). So Steven saw stuff
flushed on newlines and you would see stuff flushed when you explicitly
flush or when the buffer fills (probably doesn't happen for your use
because you need a response, and never write enough to fill the buffer).

Cameron Simpson <cs at> DoD#743

Gentle suggestions being those which are written on rocks of less than 5lbs.
        - Tracy Nelson in comp.lang.c

More information about the Python-list mailing list