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

Sahil Tandon sahil at FreeBSD.org
Thu Sep 1 22:02:54 EDT 2011


[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.

>> # process input, line-by-line, and print responses after parsing input
>> while 1:
>>    rval = parse(raw_input())
>>    if rval == None:
>>      print('foo')
>>    else:
>>      print('bar')
>> %%
>
> "while True" is considered slightly more idiomatic (readable), but
> otherwise, that seems fine.

Ah, thanks -- I've changed '1' to 'True'.

>> This works, but while reading the documentation, I thought of using 'for
>> line in fileinput.input()' in lieu of 'while 1:' construct.  This does
>> not work when debugging the program on the command line -- the script
>> appears to just hang no matter what is typed into STDIN.  I believe this
>> is because of some internal buffering when using fileinput.  Is there a
>> recommended way to disable such buffering?  Am I taking a totally wrong
>> approach?
>
> I'm not sure anything about fileinput is exactly *recommended*, it's kinda
> discouraged on account of being a bit slow. See help(fileinput) at the
> interactive prompt.
>
> For what it's worth, the default buffersize for fileinput.input is 0, so if
> that doesn't do what you want, I don't think fileinput is the right
> solution.

Got it.  Based on your and others' response, I will stick with my 
existing approach.

-- 
Sahil Tandon <sahil at FreeBSD.org>




More information about the Python-list mailing list