"Hijacking" Windows file open events using Python

751 views Asked by At

I need to combine directory watching with event "hijacking". Basically, I want my Python program to listen to a directory (and its subdirs) for when a user double-clicks (i.e. opens/acesses) the file. At that point, I want my prgm to stop the events propagation and obtain a reference to the file.

In short: for some arbitrary directory, I want all attempts at file access to come through my program first, at which point I can do what I want without interference from Windows. How can this be done?

Background: already delved into pywin32 and it seems that even the underlying windows os filesystem api doesn't have a generic file access notifier. while it claims to be there, testing reveals that for most programs calling "open" on a file, the file access timestamp is not updated unless that file is modified or saved. Really, I want something like inotify, but in all the windows ported versions i've found this "IN_OPEN" notification is stripped. I'm assuming this has to do with the underlying Windows api, but maybe I'm missing something...

Thanks,

EDIT: Oops, didn't realize this might sound spammy... The reason I need to access the file open event is so that a user can open a "stub" file which contains only metadata. This stub is then used to generate a temp file which is what ends up being passed to the appropriate application. On save, the file's contents are pushed to a decentralized, cloud storage backend. At no point does the user really have the ability to own a document on the machine. So, "hijacking" the file open is for (1) constructing a file with actual contents (2) opening that file with the correct application

2

There are 2 answers

1
theodox On BEST ANSWER

You can achieve something similar by implementing your own extension and associating it with an intermediate application (or in this case, a python script). This won't catch all file actions but will let you explicitly handle some by extension.

You can use the assoc command to register your extension with a bat file that runs your python:

https://superuser.com/questions/406985/programatically-associate-file-extensions-with-application-on-windows

0
Jonathon Reinhart On

You should check out Dokan, a usermode filesystem for Windows, very similar to FUSE which exists for *NIX operating systems. Unfortunately, there doesn't seem to be an active Python wrapper.

Dokan FUSE "is a wrapper library that makes Dokan compatible with FUSE API." With that you might be able to use a Python binding like fusepy.