Monitoring Directory 
Leopard, Python September 5th, 2008
Damn! The project sucks! We have to work on a server far away from American. Poor VPN connection, high network delay… Even though we have a local copy, no server environment up…
But Xupeng and me found a good solution for it yesterday. We ran a program for monitoring the code directory’s changes. When we modify the code, it well transfer the modified file to remote server automatically. So we just need to modify the code, and refresh the browser, haha ![]()
Xupeng has written a inotify program for doing monitoring on Linux. But my Leopard have no good file system events mechanism for it. FSEvents and kqueue can’t show what changed within the directory, so I need do some extra works for indexing the directory’s files for comparing.
Here are the code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 | from FSEvents import * import objc import os import sys import stat def fsevents_callback(streamRef, clientInfo, numEvents, eventPaths, eventMasks, eventIDs): full_path = clientInfo global previous_mtimes for i in range(numEvents): path = eventPaths[i] if path[-1] == '/': path = path[:-1] temp_mtimes = {} for dirpath, dirnames, filenames in os.walk(full_path): for filename in filenames: filename = os.path.join(dirpath, filename) new_mtime = os.path.getmtime(filename) new_size = os.path.getsize(filename) temp_mtimes[filename] = (new_mtime, new_size) if filename not in previous_mtimes: # Do some actions elif new_mtime > previous_mtimes[filename][0] and new_size != previous_mtimes[filename][1]: # Do some actions previous_mtimes = temp_mtimes def my_FSEventStreamCreate(path): streamRef = FSEventStreamCreate(kCFAllocatorDefault, fsevents_callback, path, [path], kFSEventStreamEventIdSinceNow, 1.0, 0) if streamRef is None: return None return streamRef if __name__ == "__main__": full_path = '/path/to/code/' previous_mtimes = {} # Create a files index for target directory for dirpath, dirnames, filenames in os.walk(full_path): for filename in filenames: filename = os.path.join(dirpath, filename) previous_mtimes[filename] = (os.path.getmtime(filename), os.path.getsize(filename)) streamRef = my_FSEventStreamCreate(full_path) FSEventStreamScheduleWithRunLoop(streamRef, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode) startedOK = FSEventStreamStart(streamRef) if not startedOK: exit() # Run CFRunLoopRun() #Stop / Invalidate / Release FSEventStreamStop(streamRef) FSEventStreamInvalidate(streamRef) #FSEventStreamRelease(streamRef) |