I needed pausing functionality so I'm using the following observer:
import time
import contextlib
import watchdog.observers
class PausingObserver(watchdog.observers.Observer):
def dispatch_events(self, *args, **kwargs):
if not getattr(self, '_is_paused', False):
super(PausingObserver, self).dispatch_events(*args, **kwargs)
def pause(self):
self._is_paused = True
def resume(self):
time.sleep(self.timeout) # allow interim events to be queued
self.event_queue.queue.clear()
self._is_paused = False
@contextlib.contextmanager
def ignore_events(self):
self.pause()
yield
self.resume()
I can then pause the observer directly with the pause()
and resume()
methods, but my primary use case is for when I just want to ignore any events caused by writing to a directory I'm watching, for which I use the context manager:
import os
import datetime
import watchdog.events
class MyHandler(watchdog.events.FileSystemEventHandler):
def on_modified(self, event):
with OBSERVER.ignore_events():
with open('./watchdir/modifications.log', 'a') as f:
f.write(datetime.datetime.now().strftime("%H:%M:%S") + '\n')
if __name__ == '__main__':
watchdir = 'watchdir'
if not os.path.exists(watchdir):
os.makedirs(watchdir)
OBSERVER = PausingObserver()
OBSERVER.schedule(MyHandler(), watchdir, recursive=True)
OBSERVER.start()
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
OBSERVER.stop()
OBSERVER.join()
You can test this out by saving both code blocks in a file, running it, and adding/editing/removing files in the created 'watchdir' directory. The timestamps of your modifications will be appended to 'watchdir/modifications.log'.
This functionality appears to be built into pyinotify, but that library only works in linux and watchdog is OS-independent.