Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- """ Watched Folder or Hot Folder.
- Observes a folder for file changes, e.g. new/edited/deleted files.
- inspired by: http://timgolden.me.uk/python/win32_how_do_i/watch_directory_for_changes.html
- """
- import os
- import threading
- import win32file
- import win32con
- # actions
- ACTIONS = {
- 1 : "Created",
- 2 : "Deleted",
- 3 : "Updated",
- 4 : "Renamed from something",
- 5 : "Renamed to something"
- }
- # constants
- FILE_LIST_DIRECTORY = 0x0001
- class WatchedFolder:
- def __init__(self, path):
- self.path = path
- """ path to watch """
- self.buffer = 1024
- """ buffer size for results """
- self.thread = None
- """ main thread """
- self.stopped = None
- """ set to True to stop watching """
- self.subDirs = True
- """ set to True to watch sub dirs """
- self.filter = win32con.FILE_NOTIFY_CHANGE_FILE_NAME |
- win32con.FILE_NOTIFY_CHANGE_DIR_NAME |
- win32con.FILE_NOTIFY_CHANGE_ATTRIBUTES |
- win32con.FILE_NOTIFY_CHANGE_SIZE |
- win32con.FILE_NOTIFY_CHANGE_LAST_WRITE |
- win32con.FILE_NOTIFY_CHANGE_SECURITY
- """ event filter """
- # directory handle
- self.handle = win32file.CreateFile(
- path,
- FILE_LIST_DIRECTORY,
- win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE | win32con.FILE_SHARE_DELETE,
- None,
- win32con.OPEN_EXISTING,
- win32con.FILE_FLAG_BACKUP_SEMANTICS,
- None
- )
- # run loop
- def run(self):
- while not self.stopped:
- results = win32file.ReadDirectoryChangesW(
- self.handle,
- self.buffer,
- self.subDirs,
- self.filter,
- None,
- None
- )
- self.do(results)
- # start watching
- def start(self):
- self.stopped = False
- thread = threading.Thread(target=self.run)
- thread.daemon = True
- thread.start()
- self.thread = thread
- # stop watching
- def stop(self):
- self.stopped = True
- # overwrite this
- def do(self, results):
- for action, item in results:
- fullFilename = os.path.join(self.path, item)
- print fullFilename, ACTIONS.get(action, "Unknown")
- def demo():
- import time
- path = os.path.abspath("watch")
- wf = WatchedFolder(path)
- wf.start()
- wait = 10 # wait x seconds
- print "now wait %d seconds..." % wait
- time.sleep(wait)
- print "stop!"
- wf.stop()
- print "stopped"
- # hint: after stopping, the last initiated run still is alive
- if __name__ == "__main__":
- demo()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement