pyinotify简单实用(用于文件系统监控)

    Pyinotify是一个Python模块,用来监测文件系统的变化。 Pyinotify依赖于Linux内核的功能—inotify(内核2.6.13合并)。 inotify的是一个事件驱动的通知器,其通知接口通过三个系统调用从内核空间到用户空间。pyinotify结合这些系统调用,并提供一个顶级的抽象和一个通用的方式来处理这些功能。

pyinotify其实就是通过调用系统的inotify来实现通知的。

 

1. 安装

git clone https://github.com/seb-m/pyinotify.git
cd pyinotify/
python setup.py install

2. 简单使用

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

class EventHandler(ProcessEvent):
    def process_IN_CREATE(self, event):
        print "Create file:%s." %os.path.join(event.path,event.name)

        os.system('cp -rf %s /tmp/bak/'%(os.path.join(event.path,event.name)))
    def process_IN_DELETE(self, event):
        print "Delete file:%s." %os.path.join(event.path,event.name)

    def process_IN_MODIFY(self, event):
        print "Modify file:%s." %os.path.join(event.path,event.name)

def FsMonitor(path='.'):
    wm = WatchManager()
    mask = IN_DELETE | IN_CREATE | IN_MODIFY
    notifier = Notifier(wm, EventHandler())
    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():
                print "check event true."
                notifier.read_events()
        except KeyboardInterrupt:
            print "keyboard Interrupt."
            notifier.stop()
            break

if __name__ == "__main__":
    FsMonitor("/root/work/")


 

 

 

 

 

 

 

 

 

 

 

 

 

转载于:https://my.oschina.net/zhangxu0512/blog/382867

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值