How to get a file close event in python

后端 未结 4 1635
小蘑菇
小蘑菇 2021-01-02 05:23

Using python 2.7 on windows 7 64 bit machine.

How to get a file close event:

  1. when file is opened in a new process of file opener (like notepad, wordpad
4条回答
  •  抹茶落季
    2021-01-02 05:51

    The problem you are facing is not with Python, but with Windows. It can be done, but you will have to write some non-trival C/C++ code for it.

    A file open or a file close user mode notification does not exist in userland on Windows. That's why the libraries suggested by others do not have file close notification. In Windows, the API to detect changes in userland is ReadDirectoryChangesW. It will alert you of one of the following notifications :

    • FILE_ACTION_ADDED if a file was added to the directory.
    • FILE_ACTION_REMOVED if a file was removed from the directory.
    • FILE_ACTION_MODIFIED if a file was modified. This can be a change in the time stamp or attributes.
    • FILE_ACTION_RENAMED_OLD_NAME if a file was renamed and this is the old name.
    • FILE_ACTION_RENAMED_NEW_NAME if a file was renamed and this is the new name.

    No amount of Python can change what Windows provides you with.

    To get a file close notification, tools like Process Monitor install a Minifilter that lives in the kernel, near the top of other filters like EFS.

    To acheive what you want, you would need to:

    1. Install a Minifilter that has the code to send events back to userland. Use Microsoft's Minispy sample, it is stable and fast.
    2. Convert the code from the user program to make it a Python extension (minispy.pyd) that exposes a generator that produces the events. This is the hard part, I will get back to that.
    3. You will have to filter out events, you won't beleive the amount of IO goes on an idle Windows box!
    4. Your Python program can then import your extension and do its thing.

    The whole thing looks something like this :

    A Python wrapper over a Windows Minifilter for filesystem events

    Of course you can have EFS over NTFS, this is just to show that your minifilter would be above all that.

    The hard parts :

    • Your minifilter will have to be digitally signed by an authority Microsoft trusts. Verising comes to mind but there are others.
    • Debugging requires a separate (virtual) machine, but you can make your interface easy to mock.
    • You will need to install the minifilter with an account that has adminstrator rights. Any user will be able to read events.
    • You will have to deal with multi-users your self. There is only one minifilter for many users.
    • You will have to convert user program from the MiniSpy sample to a DLL, which you will wrap with a Python extension.

    The last two are the hardest.

提交回复
热议问题