By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
440,345 Members | 1,783 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 440,345 IT Pros & Developers. It's quick & easy.

tail -f sys.stdin

P: n/a
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.

--
--arutz
Jul 19 '05 #1
Share this Question
Share on Google+
2 Replies


P: n/a
Antal Rutz <ar***@mimoza.pantel.net> wrote:
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!
Jul 19 '05 #2

P: n/a
garabik:
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'
%

Andrew
da***@dalkescientific.com

Jul 19 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.