Skip to content

Instantly share code, notes, and snippets.

@johntyree
Last active August 29, 2015 13:56
Show Gist options
  • Save johntyree/8949940 to your computer and use it in GitHub Desktop.
Save johntyree/8949940 to your computer and use it in GitHub Desktop.
inotify substitute for Windows
#!/usr/bin/env python
# coding: utf8
# GistID: 8949940
from os.path import abspath, expanduser
def on_modify(path, callback):
""" Watch a path for changes by write time, recursively.
Params
------
path : str
The path to watch
callback : callable
A callback function to be called when ``path`` changes.
"""
path_to_watch = abspath(expanduser(path))
# FindFirstChangeNotification sets up a handle for watching
# file changes. The first parameter is the path to be
# watched; the second is a boolean indicating whether the
# directories underneath the one specified are to be watched;
# the third is a list of flags as to what kind of changes to
# watch for. We're just looking at file additions / deletions.
change_handle = win32file.FindFirstChangeNotification(
path_to_watch, 0, win32con.FILE_NOTIFY_CHANGE_LAST_WRITE)
# Loop forever, listing any file changes. The WaitFor... will
# time out every half a second allowing for keyboard interrupts
# to terminate the loop.
try:
while True:
result = win32event.WaitForSingleObject(change_handle, 500)
# If the WaitFor... returned because of a notification (as
# opposed to timing out or some error) then look for the
# changes in the directory contents.
if result == win32con.WAIT_OBJECT_0:
try:
callback()
except Exception as e:
print "Exception: {}".format(e)
win32file.FindNextChangeNotification(change_handle)
finally:
win32file.FindCloseChangeNotification(change_handle)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment