Skip to content

Instantly share code, notes, and snippets.

@antsankov
Last active February 1, 2016 16:22
Show Gist options
  • Save antsankov/192cf0d45337993baadd to your computer and use it in GitHub Desktop.
Save antsankov/192cf0d45337993baadd to your computer and use it in GitHub Desktop.
Watchdog Test
import sys
import time
import logging
from watchdog.observers import Observer
from watchdog.events import *
#http://stackoverflow.com/questions/18599339/python-watchdog-monitoring-file-for-changes
class MyHandler(LoggingEventHandler):
#this creates the list of paths
def __init__(self):
self.paths = []
#this runs when a file is modified
def on_modified(self,event):
#checks if the src path is in the queue of paths
if (event.src_path) in self.paths:
#if it is, remove it and print the new path
self.paths.remove(event.src_path)
print("OLD " +", ".join(self.paths))
else:
#if it isn't in the queue, and isn't '.' then add it in.
if (event.src_path != '.'):
self.paths.append(event.src_path)
#print out the new path
print("NEW " +", ".join(self.paths))
def on_created(self,event):
print("FILE CREATED")
def test_function():
print("File was modified!")
#we can parse the new file for differences
if __name__ == "__main__":
print("watchdog up")
logging.basicConfig(level=logging.INFO,format='%(asctime)s - %(message)s',datefmt='%Y-%m-%d %H:%M:%S')
#right now I just use the most basic handler, but we couuld use regex or pattern handler.
my_handler = MyHandler()
l_handler = LoggingEventHandler()
r_handler=RegexMatchingEventHandler(regexes=['.*'], ignore_regexes=[], ignore_directories=False, case_sensitive=False)
p_handler=PatternMatchingEventHandler(patterns =None, ignore_patterns=[],ignore_directories=False, case_sensitive=False)
#we need to create an actual observer.
observer = Observer()
#we feed the event handler the observer, with the proper
observer.schedule(my_handler, '.', recursive=True)
observer.start()
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
observer.stop()
observer.join()
@mmonaco
Copy link

mmonaco commented Oct 30, 2014

Okay, so now we need to come up with a good way of ignoring changes made by ourselves. That said, I don't like how watchdog only allows monitoring on directories. We might want to use pyinotify instead.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment