Check if file is modified deleted or extended usin

2019-09-06 18:45发布

问题:

Hi I am having a hard time understanding how to use the BSD only python module classes select.kqueue and select.kevent to setup a watch for file write events.

I want to a python program to respond whenever a text file is written to by another process. My test code goes as follows:

    import os
    myfd = os.open("/Users/hari/c2cbio/t.txt",os.O_RDONLY)
    my_event=select.kevent(myfd,filter=select.KQ_FILTER_VNODE,fflags=select.KQ_NOTE_WRITE|select.KQ_NOTE_EXTEND)

    # I now create a kqueue object and a control object

    kq = select.kqueue()
    # I dont know how to set the max_events if it is non zero the REPL does not return
    kq.control([my_event],0,None)

I dont know How to proceed to check that these events have indeed happened. Can someone point me to an example of using kqueue to detect file modification or any other events ( like file delete , file rename etc)

回答1:

Looking at the code for the watchdog module I came up with this . I dont know if the flags are necessary.

#/usr/bin/env python
import select
import os

kq = select.kqueue()
# Use the OSX specific os.EVTONLY
# http://code.google.com/p/python-watchdog/source/browse/src/watchdog/observers/kqueue.py
fd = os.open("/Users/hari/c2cbio/t.txt", 0x8000)

ev = [select.kevent(fd, filter=select.KQ_FILTER_VNODE,flags=select.KQ_EV_ADD | select.KQ_EV_ENABLE | select.KQ_EV_CLEAR,fflags=select.KQ_NOTE_WRITE | select.KQ_NOTE_EXTEND)]
#This call will block till the write or extend events occur
evts = kq.control(ev,1,None)
print "event occurred"