tail -f sys.stdin

Andrew Dalke dalke at dalkescientific.com
Thu Jun 9 18:51:30 CEST 2005

> what about:
> for line in sys.stdin:
>     process(line)

This does not meet the OP's requirement, which was
>> I'd like to write a prog which reads one line at a time on its sys.stdin
>> and immediately processes it.
>> If there are'nt any new lines wait (block on input).

It's a subtle difference.  The implementation of iter(file)
reads a block of data at a time and breaks that into lines,
along with the logic to read another block as needed.  If
there isn't yet enough data for the block then Python will
sit there waiting.

The OP already found the right solution which is to call
the "readline()" method.

Compare the timestamps in the following

% ( echo "a" ; sleep 2 ; echo "b" ) | python -c "import sys, time\        
    for line in sys.stdin:\                                               
      print time.time(),  repr(line)"

1118335675.45 'a\n'
1118335675.45 'b\n'
% ( echo "a" ; sleep 2 ; echo "b" ) | python -c "import sys, time\
    while 1:\
        line = sys.stdin.readline()\
        if not line: break \
        print time.time(), repr(line)"
1118335678.56 'a\n'
1118335680.28 'b\n'

				dalke at dalkescientific.com

More information about the Python-list mailing list