Sunday, February 5, 2012

Python: buffering problem when using 'for line in sys.stdin'

Nowadays, I found a buffering problem when I use the following python code:
for line in sys.stdin:
print line

using which after I type in a sentence to the terminal, I get no output.

After investigating for a while, I come to the following solution (using readline() instead):
infile=sys.stdin
line=' '
while len(line)!=0:
line=infile.readline()
print line

1 comment:

Unknown said...

Mr. Wang Pidong,
This issue had been causing me great grief on an IPC programming assignment involving both C and python. This buffering turned out to be the culprit. Thank you good sir!
Dan