启用文件夹观察程序的启动,停止功能

时间:2012-07-07 06:12:28

标签: python pyinotify

下面的代码不能像我想要的那样工作。当我svc.run()时,程序运行正常。我对我的文件夹工作文件所做的任何更改。但是当我做svc.stop()时,我认为它并没有完全停止。也许必须有更好的方法来做线程部分...

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 was %s' % (os.path.join(path, name), operation)


p = '/home/deostroll/scripts/tmp'
svc = NotificationService(p, _callback)
svc.run()

1 个答案:

答案 0 :(得分:1)

我不熟悉pyinorify,但似乎self.__notifier.process_events()阻塞,所以self.__loop在某些事件发生之前不会被读取。

您可以改为使用pyinotify.ThreadedNotifier

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'