tail -f sys.stdin

A

Antal Rutz

Hi!

Maybe a very newbie question but:
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).

I couldn't find a solution for it.
Several methods that doesn't fit here:
- reading the entire file-like object until EOF and then process
- read one line(all lines) and when there aren't any lines more, quit.

So I need a 'tail -f' for stdin.

Thanks.
 
G

garabik-news-2005-05

Antal Rutz said:
Hi!

Maybe a very newbie question but:
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).

what about:

for line in sys.stdin:
process(line)

--
-----------------------------------------------------------
| Radovan Garabík http://kassiopeia.juls.savba.sk/~garabik/ |
| __..--^^^--..__ garabik @ kassiopeia.juls.savba.sk |
-----------------------------------------------------------
Antivirus alert: file .signature infected by signature virus.
Hi! I'm a signature virus! Copy me into your signature file to help me spread!
 
A

Andrew Dalke

garabik:
what about:

for line in sys.stdin:
process(line)

This does not meet the OP's requirement, which was
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'
%

Andrew
(e-mail address removed)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,995
Messages
2,570,235
Members
46,821
Latest member
AleidaSchi

Latest Threads

Top