用pyinotify监控Linux文件系统

1、install pyinotify library on the Linux OS

if you have already installed pip :

pip install pyinotify  

this command line to install pyinotify

if you have't install pip

for python3:

sudo apt-get install python3-pip

for python2

sudo apt-get install python-pip

after installed pip.

for python3:

pip3 install pyinotify

for python2:

pip install pyinotify

2、pyinotify

Module event

pyinotify.ProcessEvent is the base class of pyinotify

IN_ACCESS when the file is accessed

IN_MODIFY when the file is writed

IN_ATTRIB. when the Attributes of the file is be modified such as chmod、chown、touch

IN_CLOSE_WRITE when writable file be closed

IN_CLOSE_NOWRITE when unwritable file be closed

IN_OPEN when the file is opened

IN_MOVED_FROM. when the file has be moved such as the command line mv

IN_MOVED_TO when the file has be moved to here such as the command line mv and cp

IN_CREATE when create a new file

IN_DELETE when the file is deleted such as the command line sudo rm -rf

IN_DELETE_SELF when the file delete itself

IN_MOVE_SELF when the file move itself

IN_UNMOUNT when host file system is umounted

IN_CLOSE when the file is closed equals to (IN_CLOSE_WRITE | IN_CLOSE_NOWRITE)

IN_MOVE when the file is moved equals to (IN_MOVED_FROM | IN_MOVED_TO)

(2) Instance

wm = pyinotify.WatchManager()   // instance monitor

wm.add_watch(path, pyinotify.ALL_EVENTS, res = True) # add Monitored object

notifier = pyinotify.Notifier(wm,ev) # binding a event

notifier.loop() # run to monitor

(3) for example (show me the code)


import os 

from pyinotify import WatchManager, Notifier, ProcessEvent, IN_DELETE, IN_CREATE, IN_MODIFY

class EvenHandler(ProcessEvent):

    #C1_str = ""
    #C2_str = ""
    #C3_str = ""

    def process_IN_CREATE(self, event):
        print("Createfile: % s" % os.path.join(event.path, event.name))

    def process_IN_DELETE(self, event):
        print("Deletefile: % s" % os.path.join(event.path, event.name))

    def process_IN_MODIFY(self, event):
        print("Modifyfile: % s" % os.path.join(event.path, event.name))
        #if os.path.join(event.path, event.name) == "/var/www/Receive_data/people_recognition/coordinates/C1.txt":
            #with open("/var/www/Receive_data/people_recognition/coordinates/C1.txt",'r') as f:
                #self.C1_str = f.readline()
                #print(self.C1_str)
        #if os.path.join(event.path, event.name) == "/var/www/Receive_data/people_recognition/coordinates/C2.txt":
            #with open("/var/www/Receive_data/people_recognition/coordinates/C2.txt",'r') as f:
                #self.C2_str = f.readline()
                #print(self.C2_str)
        #elif os.path.join(event.path, event.name) == "/var/www/Receive_data/people_recognition/coordinates/C3.txt":
            #with open("/var/www/Receive_data/people_recognition/coordinates/C3.txt",'r') as f:
                #self.C3_str = f.readline()
                #print(self.C3_str)
        #if(self.C1_str != "" and self.C2_str != "" and self.C3_str != ""):
            #print("all has been collected!")
            #self.C1_str = ""
            #self.C2_str = ""
            #self.C3_str = ""
        #else:
            #print("make sure that the program can get here")
def FSMonitor(path):
    wm = WatchManager()

    mask = IN_CREATE | IN_DELETE | IN_MODIFY
    #mask = IN_MODIFY

    notifier = Notifier(wm, EvenHandler())

    wm.add_watch(path, mask, auto_add=True, rec=True)

    print("now starting monitor %s " % (path))

    while True:

        try:
            notifier.process_events()

            if notifier.check_events():

                notifier.read_events()

        except KeyboardInterrupt:

            notifier.stop()

            break

if __name__ == "__main__":
    FSMonitor('/var/www/Receive_data/people_recognition/coordinates')
    # FSMonitor('/var/www/Receive_data/people_recognition/coordinates/C2.txt')
    # FSMonitor('/var/www/Receive_data/people_recognition/coordinates/C3.txt')

原谅我很烂的英文水平,将就一下~

The uncommented code I post above implement the basic function. You can add the function you need.
------------------------------------分割线-------------------------------------

Next I will record my experience about what I need to implement and how to do and Not related to the content of the post!!!!

Demands:

There are several client need to post the data to the server, then the server needs to caculate the distance between the each other
The problem is the data comes from different client and the requests is the different . There are two ways to solve it.One is to save the data to the database , the other is to save the data to the file. therefore , I choose to use a file to save it and I use a program to monitor the file when the file has been modified will trigger a function which read the file to get the data and save it.
The good news is the file in the same directory , so i only need to monitor this directory.

os.path.join(event.path, event.name)

this code will get the path of which file has been modified. The class of EventHandler has three variables map three files. when one of the three file has been modified the variable will get the data and when the three variables have a value of the data will caculate the distance between each other. when it's done , The three variable will be set to "" wait to receive the new data.

There is a trick

def format_data(str):
    x,y = 0,0
    divide = str.split(',')
    x = int(divide[0].split('(')[1])
    y = int(divide[1].split(')')[0])
    # print(x,y)
    return x,y

like this function when it return x,y. The return value depend on how to use it.When i use

format_data(C1_str) 

as a param to give

Point(format_data(C1_str)) 

What i expect is that function return x,y to be the init params to instance Point class,but actually

self.x = (x,y) self.y = 0

so i use

x,y = format_data(C1_str)

to receive the return value and given to the Point() init function.
This is a noteworthy place. I got wrong in here for a long time to solve it.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 12,196评论 0 10
  • 第一,“从来日夜不闭户,过往未见人拾遗” 第二,“进门须鞠躬,过路先捂鼻” 第三,“既来想得大解脱(大便),进站定...
    雄年必浪阅读 4,125评论 0 3
  • 因为是做APP开发,所以对网络的了解肯定不如做网络开发的童鞋们,下面只是我觉得与APP开发相关的一些点,不足之处见...
    猿来如此阅读 4,130评论 0 4
  • 最爱唐晶,善良有原则,够仗义够坦荡,也拿得起和放的下,身上充满霸气。
    魔都Amy阅读 1,220评论 0 0
  • 鑫创恒汽修阅读 1,157评论 0 0

友情链接更多精彩内容