Skip to content

Instantly share code, notes, and snippets.

@luke10x
Created April 16, 2014 22:11
Show Gist options
  • Save luke10x/10938115 to your computer and use it in GitHub Desktop.
Save luke10x/10938115 to your computer and use it in GitHub Desktop.
Process that monitors file system changes within directory and runs scripts on changed entities
#!/usr/bin/python
import gamin
import time
from os.path import expanduser
import threading
import thread
import os
import Queue
class CallbackFactory():
"""
Callback for file change monitor events
"""
def __init__(self, monitor, dir, queue):
self.dir = dir
self.mon = monitor.mon
self.monitor = monitor
self.queue = queue
self.EVENT_CHANGED = 1
self.EVENT_DELETED = 2
self.EVENT_START_EXECUTING = 3
self.EVENT_STOP_EXECUTING = 4
self.EVENT_CREATED = 5
self.EVENT_MOVED = 6
self.EVENT_ACKNOWLEDGE = 7
self.EVENT_EXISTS = 8
self.EVENT_END_EXIST = 9
def callback(self, path, event):
if event == self.EVENT_CREATED:
created_path = self.dir + '/' + path
if os.path.isdir(created_path):
f = CallbackFactory(self.monitor, created_path,
self.queue)
self.mon.watch_directory(created_path, f.callback)
# Notify about all files in the created directory
# ...
print "Created:", created_path
if event == self.EVENT_DELETED:
print "Deleted:", path
if event == self.EVENT_CHANGED:
print "Changed:", path
if event == self.EVENT_MOVED:
print "Moved:", path
if event == self.EVENT_ACKNOWLEDGE:
print "Ack:", path
self.queue.put(path)
class MonitorThread(threading.Thread):
def __init__(self, queue):
threading.Thread.__init__(self)
self.dir = expanduser('~/Desktop')
self.mon = gamin.WatchMonitor()
self.queue = queue
def add_directories(self):
f = CallbackFactory(self, self.dir, self.queue)
self.mon.watch_directory(self.dir, f.callback)
for root, folders, files in os.walk(self.dir):
for folder in folders:
dir = root + "/" + folder
f = CallbackFactory(self, dir, self.queue)
self.mon.watch_directory(dir, f.callback)
print dir
def run(self):
print "Starting monitoring"
self.add_directories()
print "Entering infinite loop"
while True:
time.sleep(5)
ret = self.mon.event_pending()
if ret > 0:
# ret = self.mon.handle_one_event()
ret = self.mon.handle_events()
self.mon.stop_watch(self.dir)
del self.mon
print "Exiting monitoring"
class Processor(threading.Thread):
def __init__(self, queue):
threading.Thread.__init__(self)
self.queue = queue
def run(self):
while True:
url = self.queue.get()
self.process_file(url)
self.queue.task_done()
def process_file(self, url):
print "Processing file:", url
queue = Queue.Queue()
t = Processor(queue)
t.daemon = True
t.start()
monitor = MonitorThread(queue)
monitor.daemon = True
monitor.start()
try:
while True: time.sleep(100)
except (KeyboardInterrupt, SystemExit):
print "INTERRUPTED"
print "Main thread ends here"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment