python - enabling start, stop feature for a folder watcher program -


the code below doesn't work want to. when svc.run() programs runs okay. changes i've made folder works file. when svc.stop() doesn't stop think. perhaps there must better way of doing threading part...

import pyinotify import threading import time import os class fs_event_handler(pyinotify.processevent): def __init__(self, callback): self._callback = callback def process_in_create(self, e): self._callback(e.path, e.name, 'created') def process_in_delete(self, e): self._callback(e.path, e.name, 'deleted') def process_in_modify(self, e): self._callback(e.path, e.name, 'modified') class notificationservice(): def __init__(self, path, callback): mask = pyinotify.in_create | pyinotify.in_delete \ | pyinotify.in_modify w = pyinotify.watchmanager() self.__notifier = pyinotify.notifier(w, fs_event_handler(callback)) wdd = w.add_watch(path, mask, rec=true, auto_add=true) self.__loop = true def start(self): while self.__loop: self.__notifier.process_events() if self.__notifier.check_events(): self.__notifier.read_events() def run(self): fm = filemonitor(self) fm.start() print 'service running...' def stop(self): self.__notifier.stop() self.__loop = false class filemonitor(threading.thread): def __init__(self, srvc): threading.thread.__init__(self) self.__svc = srvc def run(self): self.__svc.start() print 'service stopped' def _callback(path, name, operation): zpad = lambda x: ''.join(['0', str(x)])[:2] ts = time.localtime() t = ':'.join(map(zpad, [ts.tm_hour, ts.tm_min, ts.tm_sec])) print t, ':', '%s %s' % (os.path.join(path, name), operation) p = '/home/deostroll/scripts/tmp' svc = notificationservice(p, _callback) svc.run() 

i'm not familiar pyinorify, seems self.__notifier.process_events() blocks self.__loop doesn't read until event happens.

you can use pyinotify.threadednotifier instead:

class notificationservice(): def __init__(self, path, callback): self.path = path self.callback = callback def start(self): mask = pyinotify.in_create | pyinotify.in_delete \ | pyinotify.in_modify w = pyinotify.watchmanager() wdd = w.add_watch(self.path, mask, rec=true, auto_add=true) self.__notifier = pyinotify.threadednotifier(w, fs_event_handler(self.callback)) self.__notifier.start() print 'service running...' def run(self): self.start() def stop(self): self.__notifier.stop() print 'service stopped' 

Comments

Popular posts from this blog

javascript - backbone.js Collection.add() doesn't `construct` (`initialize`) an object -

php - Get uncommon values from two or more arrays -

Adding duplicate array rows in Php -