[Tutor] What am I missing?

Kent Johnson kent_johnson at skillsoft.com
Mon Sep 27 11:59:28 CEST 2004


Brian,

The variable found is assigned each time through the loop. re.search() will 
return either a Match object or None and found will have one of these 
values assigned to it. There is no need to re-assign a False value to found.

Kent

At 12:32 AM 9/27/2004 -0400, Brian van den Broek wrote:
>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
>_______________________________________________
>Tutor maillist  -  Tutor at python.org
>http://mail.python.org/mailman/listinfo/tutor



More information about the Tutor mailing list