Created
October 16, 2021 21:13
-
-
Save dmwyatt/cf0627b777aad08856cf71ac7df4819a to your computer and use it in GitHub Desktop.
[monitor windows files] Monitors files and folders or directories. #system #windows
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
import time | |
from pathlib import Path | |
import pywintypes | |
import win32con | |
import win32file | |
import winerror | |
WATCHED_DIR = str(Path("./").absolute()) | |
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 | |
| win32con.FILE_SHARE_WRITE # shareMode | |
| win32con.FILE_SHARE_DELETE, | |
None, # attributes | |
win32con.OPEN_EXISTING, # CreationDisposition | |
win32con.FILE_FLAG_BACKUP_SEMANTICS | |
| win32con.FILE_FLAG_OVERLAPPED, # flagsAndAttributes # async | |
None, # hTemplateFile | |
) | |
while True: | |
# read directory changes async | |
win32file.ReadDirectoryChangesW( | |
hDir, # handle | |
buf, # buffer | |
True, # bWatchSubtree | |
win32con.FILE_NOTIFY_CHANGE_FILE_NAME | |
| win32con.FILE_NOTIFY_CHANGE_DIR_NAME # dwNotifyFilter | |
| 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, ol, False # hFile # overlapped # 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) | |
print("---") | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment