加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

用pyinotify监控文件系统示例

发布时间:2020-12-17 17:24:13 所属栏目:Python 来源:网络整理
导读:今天PHP站长网 52php.cn把收集自互联网的代码分享给大家,仅供参考。 ??? Pyinotify是一个Python模块,用来监测文件系统的变化。 Pyinotify依赖于Linux内核的功能—inotify(内核2.6.13合并)。 inotify的是一个事件驱动

以下代码由PHP站长网 52php.cn收集自互联网

现在PHP站长网小编把它分享给大家,仅供参考

??? Pyinotify是一个Python模块,用来监测文件系统的变化。 Pyinotify依赖于Linux内核的功能—inotify(内核2.6.13合并)。 inotify的是一个事件驱动的通知器,其通知接口通过三个系统调用从内核空间到用户空间。pyinotify结合这些系统调用,并提供一个顶级的抽象和一个通用的方式来处理这些功能。
git clone https://github.com/seb-m/pyinotify.git
cd pyinotify/
python setup.py install
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/")

以上内容由PHP站长网【52php.cn】收集整理供大家参考研究

如果以上内容对您有帮助,欢迎收藏、点赞、推荐、分享。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读