| 53 | if event.mask not in (ISDIR|OPEN, ISDIR|CLOSE): print event |
| 54 | |
| 55 | class Watcher(object): |
| 56 | def __init__(self): |
| 57 | self.inotify=Inotify() |
| 58 | self.watches={} |
| 59 | self.queue=Queue() |
| 60 | self.lock=RLock() |
| 61 | for t in (self._push, self._pull): |
| 62 | t=Thread(target=t) |
| 63 | t.setDaemon(True) |
| 64 | t.start() |
| 65 | def _push(self): |
| 66 | while True: |
| 67 | for wd, mask, cookie, name in self.inotify.read(): |
| 68 | self.queue.put(Event(wd, self, mask, cookie, name)) |
| 69 | def _pull(self): |
| 70 | while True: |
| 71 | event = self.queue.get() |
| 72 | mask=event.mask |
| 73 | self.lock.acquire() |
| 74 | watch = self.watches.get(event.wd) |
| 75 | self.lock.release() |
| 76 | watch.callback(event) |
| 77 | if mask&ISDIR and mask&CREATE and watch.auto: |
| 78 | self.add(event.path, watch.mask, |
| 79 | watch.callback, auto=True, _parent=watch) |
| 80 | if mask&IGNORED: |
| 81 | self.rem(watch) |
| 82 | def add(self, path, mask=ALL, callback=default, auto=True, _parent=None): |
| 83 | self.lock.acquire() |
| 84 | wd=self.inotify.add_watch(path, mask) |
| 85 | watch = Watch(wd, self, mask, path, callback, auto, _parent) |
| 86 | self.watches[wd] = watch |
| 87 | self.lock.release() |
| 88 | return watch |
| 89 | def rem(self, watch): |
| 90 | self.lock.acquire() |
| 91 | for w in list(self.watches.values()): |
| 92 | if w._parent==watch: self.rem(w) |
| 93 | wd=watch.wd |
| 94 | self.watches.pop(wd) |
| 95 | self.lock.release() |
| 96 | def close(self): |
| 97 | self.inotify.close() |
| 98 | |
| 99 | if __name__ == '__main__': |
| 100 | |