Created
April 10, 2015 18:48
-
-
Save whacked/53bd555da32d6d7b989f to your computer and use it in GitHub Desktop.
watchdog skeleton
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
# ref http://pythonhosted.org//watchdog/quickstart.html#a-simple-example | |
''' | |
watchdog skeleton | |
''' | |
import sys | |
import time | |
import datetime | |
import logging | |
from watchdog.observers import Observer | |
from watchdog.events import LoggingEventHandler, PatternMatchingEventHandler | |
import random | |
import os | |
from termcolor import colored | |
def reprocess_file(filepath): | |
print 'REPROC %s! %s' % (colored('FILE', 'red'), filepath) | |
return | |
class MyHandler(PatternMatchingEventHandler): | |
# patterns = [] # whatever you want | |
ignore_patterns = [ | |
'./.*', | |
'.*.swp', | |
'*.pyc', | |
'venv/*', | |
] | |
# for vim style edit = delete, then create | |
_previous_deletion = None | |
def on_created(self, event): | |
if event.is_directory: | |
return | |
print('{} {}'.format(colored('created', 'green'), event.src_path)) | |
if self._previous_deletion \ | |
and self._previous_deletion == event.src_path: | |
reprocess_file(event.src_path) | |
self._previous_deletion = None | |
def on_modified(self, event): | |
if event.is_directory: | |
return | |
print('{} {}'.format(colored('modified', 'yellow'), event.src_path)) | |
reprocess_file(event.src_path) | |
self._previous_deletion = None | |
def on_deleted(self, event): | |
if event.is_directory: | |
return | |
print('{} {}'.format(colored('deleted', 'red'), event.src_path)) | |
self._previous_deletion = event.src_path | |
if __name__ == "__main__": | |
logging.basicConfig(level=logging.INFO, | |
format='%(asctime)s - %(message)s', | |
datefmt='%Y-%m-%d %H:%M:%S') | |
if len(sys.argv) > 1 and sys.argv[-1][0] != '-': | |
watch_dir = os.path.expanduser(sys.argv[-1]) | |
else: | |
watch_dir = '.' | |
print('watching: %s' % watch_dir) | |
# event_handler = LoggingEventHandler() | |
event_handler = MyHandler() | |
observer = Observer() | |
observer.schedule(event_handler, watch_dir, 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