[Tutor] What am I missing?
Brian van den Broek
bvande at po-box.mcgill.ca
Mon Sep 27 06:32:46 CEST 2004
Tom Tucker said unto the world upon 2004-09-26 23:58:
> Good evening! Any thoughts on this one?
>
> The goal is to 'tail -f /var/log/messages' and if the line contains
> "CROND" for example, then print that line. The below script does a
> great job of tailing and printing, but it prints EVERYTHING.
>
> ##################
> #!/usr/bin/python
>
> import os, re
>
> findme = re.compile('CROND')
> logfile = os.system('tail -f /var/log/messages')
> for line in logfile:
> found = re.search(findme, line)
> if found:
> print line,
> else:
> print "not found"
> ####################
>
>
> Thanks,
>
> Tom
Hi Tom,
with the line:
> found = re.search(findme, line)
you assign found a value which evaluates as True.
Then, for each subsequent line through the for loop you are testing if
found evaluates as True. And it does, because you made it so. ;-)
One fix would be to say this instead:
if found:
print line,
found = '' # or [], (), None, etc. Anything that
# evaluates as False will do.
Then, next time through, your if test will fail (unless of course your
re.search matched again).
I'm not sure of your intent; if you want "not found" to be printed only
when you had no matches, you will need to add a bit more.
HTH,
Brian vdB
More information about the Tutor
mailing list