I want to catch change in security permission of file without blocking till the change is made, like an event that popup when the change is made.
I also don't want to install any third party modules or softwares.
The main requirement of this is to be in some of win32
modules or built-in modules.
I'm currently watching for security change by this function:
import win32con, win32file
def security_watcher():
specific_file = "specific.ini"
path_to_watch = "."
FILE_LIST_DIRECTORY = 0x0001
hDir = win32file.CreateFile(path_to_watch,
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)
results = win32file.ReadDirectoryChangesW(hDir,
1024,
False,
win32con.FILE_NOTIFY_CHANGE_SECURITY,
None,
None)
print results
for action, file_name in results:
if file_name == specific_file:
# wake another function to do something about that
Note: I need it non blocking because I use this function in GUI Application and it freezes the GUI.
If you don't mind (or can't avoid) adding some threading overhead, you can launch a separate process or thread that waits on the blocking call to win32.ReadDirectoryChangesW()
that you already have. When it receives a change, it writes the result to a pipe shared with the main thread of your GUI.
Your GUI can periodically execute a non-blocking read at the appropriate point in your code (presumably, where you now call win32file.ReadDirectoryChangesW()
). Do make sure to wait a bit between reads, or your app will spend 100% of its time on non-blocking reads.
You can see in this answer how to set up a non-blocking read on a pipe in an OS-independent way. The final bit will look like this:
try:
results = q.get_nowait()
except Empty:
pass
else:
for line in results.splitlines():
# Parse and use your result format
...
if file_name == specific_file:
...