Created
December 9, 2018 17:46
-
-
Save tiagoad/7cd1db2cd2b39c705d76d027e1fa66f4 to your computer and use it in GitHub Desktop.
Monitors a directory (and its' children) for changes on Windows, asynchronously (overlapped mode).
This file contains 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
# Based partially on http://timgolden.me.uk/python/win32_how_do_i/watch_directory_for_changes.html (thanks!) | |
import os | |
import time | |
import win32file | |
import win32con | |
import pywintypes | |
import winerror | |
WATCHED_DIR = "./mon" | |
FILE_ACTIONS = { | |
1 : "created", | |
2 : "deleted", | |
3 : "updated", | |
4 : "renamed from", | |
5 : "renamed to" | |
} | |
def main(): | |
ol = pywintypes.OVERLAPPED() | |
buf = win32file.AllocateReadBuffer(1024) | |
# get directory handle | |
hDir = win32file.CreateFile ( | |
WATCHED_DIR, # fileName | |
0x0001, # FILE_LIST_DIRECTORY # desiredAccess | |
win32con.FILE_SHARE_READ | # shareMode | |
win32con.FILE_SHARE_WRITE | | |
win32con.FILE_SHARE_DELETE, | |
None, # attributes | |
win32con.OPEN_EXISTING, # CreationDisposition | |
win32con.FILE_FLAG_BACKUP_SEMANTICS | # flagsAndAttributes | |
win32con.FILE_FLAG_OVERLAPPED, # async | |
None # hTemplateFile | |
) | |
while True: | |
# read directory changes async | |
win32file.ReadDirectoryChangesW( | |
hDir, # handle | |
buf, # buffer | |
True, # bWatchSubtree | |
win32con.FILE_NOTIFY_CHANGE_FILE_NAME | # dwNotifyFilter | |
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, | |
ol # overlapped | |
) | |
bytes = None | |
# wait for changes | |
while bytes == None: | |
try: | |
bytes = win32file.GetOverlappedResult( | |
hDir, # hFile | |
ol, # overlapped | |
False # bWait | |
) | |
except pywintypes.error as err: | |
if err.winerror == winerror.ERROR_IO_INCOMPLETE: | |
# not available yet, wait for a bit | |
time.sleep(0.1) | |
else: | |
# other error... | |
raise err | |
# get changes from buffer | |
result = win32file.FILE_NOTIFY_INFORMATION(buf, bytes) | |
# print results | |
for action, filename in result: | |
print(FILE_ACTIONS.get(action, "Unknown"), filename) | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment