How to get a file close event in python

后端 未结 4 1618
小蘑菇
小蘑菇 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 06:06

    You can use Pyfanotyfi or butter.

    I think you'll find this link very usefull: Linux file system events with C, Python and Ruby

    There you will find an example about doing exactly what you want(using pyinotify) this is the code:

    import pyinotify
    
    DIR_TO_WATCH="/tmp/notify-dir"
    FILE_TO_WATCH="/tmp/notify-dir/notify-file.txt"
    
    wm = pyinotify.WatchManager()
    
    dir_events = pyinotify.IN_DELETE | pyinotify.IN_CREATE
    file_events = pyinotify.IN_OPEN | pyinotify.IN_CLOSE_WRITE | pyinotify.IN_CLOSE_NOWRITE
    
    class EventHandler(pyinotify.ProcessEvent):
        def process_IN_DELETE(self, event):
            print("File %s was deleted" % event.pathname) #python 3 style print function
        def process_IN_CREATE(self, event):
            print("File %s was created" % event.pathname)
        def process_IN_OPEN(self, event):
            print("File %s was opened" % event.pathname)
        def process_IN_CLOSE_WRITE(self, event):
            print("File %s was closed after writing" % event.pathname)
        def process_IN_CLOSE_NOWRITE(self, event):
            print("File %s was closed after reading" % event.pathname)
    
    event_handler = EventHandler()
    notifier = pyinotify.Notifier(wm, event_handler)
    
    wm.add_watch(DIR_TO_WATCH, dir_events)
    wm.add_watch(FILE_TO_WATCH, file_events)
    
    notifier.loop()
    

提交回复
热议问题