monitor reading file with thread
Aahz
aahz at pythoncraft.com
Mon Jan 18 17:11:37 EST 2010
In article <4b47712a$0$1115$4fafbaef at reader4.news.tin.it>,
wiso <gtu2003 at alice.it> wrote:
>
>class Reader():
> def __init__(self,filename):
> self.filename = filename
> self.lineno = 0
> def __iter__(self):
> f = open(self.filename)
> for line in f:
> self.lineno += 1
> time.sleep(0.01) # slow down
> yield line
> f.close()
There's no reason for the sleep.
>class Monitor(threading.Thread):
> def __init__(self,reader,stop_queue,interval=2):
> threading.Thread.__init__(self)
> self.interval = interval
> self.reader = reader
> self.stop_queue = stop_queue
> def run(self):
> while True:
> try:
> if self.stop_queue.get(timeout=self.interval) == "stop":
> break
> except Queue.Empty:
> pass
> print "MONITOR: ", reader.lineno
I'd make this simpler, you only need a queue when you're transferring
data between threads:
class Monitor(threading.Thread):
def __init__(self, reader, interval=2):
threading.Thread.__init__(self)
self.interval = interval
self.reader = reader
self.stop = False
def run(self):
while not self.stop:
print "MONITOR:", reader.lineno
time.sleep(self.interval)
...and to stop the monitor, just set m.stop=True. Note that you have a
bug that needs fixing, I left it for you. ;-)
--
Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/
"If you think it's expensive to hire a professional to do the job, wait
until you hire an amateur." --Red Adair
More information about the Python-list
mailing list