Skip to content

Instantly share code, notes, and snippets.

@antsankov
Created November 21, 2014 19:16
Show Gist options
  • Save antsankov/c1b3b224bc4cb938792d to your computer and use it in GitHub Desktop.
Save antsankov/c1b3b224bc4cb938792d to your computer and use it in GitHub Desktop.
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):
#make this a set not a list
self.paths = set([])
#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.add(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()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment