用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.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 215,076评论 6 497
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 91,658评论 3 389
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 160,732评论 0 350
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 57,493评论 1 288
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 66,591评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,598评论 1 293
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,601评论 3 415
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,348评论 0 270
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,797评论 1 307
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,114评论 2 330
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,278评论 1 344
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,953评论 5 339
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,585评论 3 322
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,202评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,442评论 1 268
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,180评论 2 367
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,139评论 2 352

推荐阅读更多精彩内容

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