Python文件监听工具pyinotify与watchdog实例


Posted in Python onOctober 15, 2018

pyinotify库

支持的监控事件

@cvar IN_ACCESS: File was accessed.
@type IN_ACCESS: int
@cvar IN_MODIFY: File was modified.
@type IN_MODIFY: int
@cvar IN_ATTRIB: Metadata changed.
@type IN_ATTRIB: int
@cvar IN_CLOSE_WRITE: Writtable file was closed.
@type IN_CLOSE_WRITE: int
@cvar IN_CLOSE_NOWRITE: Unwrittable file closed.
@type IN_CLOSE_NOWRITE: int
@cvar IN_OPEN: File was opened.
@type IN_OPEN: int
@cvar IN_MOVED_FROM: File was moved from X.
@type IN_MOVED_FROM: int
@cvar IN_MOVED_TO: File was moved to Y.
@type IN_MOVED_TO: int
@cvar IN_CREATE: Subfile was created.
@type IN_CREATE: int
@cvar IN_DELETE: Subfile was deleted.
@type IN_DELETE: int
@cvar IN_DELETE_SELF: Self (watched item itself) was deleted.
@type IN_DELETE_SELF: int
@cvar IN_MOVE_SELF: Self (watched item itself) was moved.
@type IN_MOVE_SELF: int
@cvar IN_UNMOUNT: Backing fs was unmounted.
@type IN_UNMOUNT: int
@cvar IN_Q_OVERFLOW: Event queued overflowed.
@type IN_Q_OVERFLOW: int
@cvar IN_IGNORED: File was ignored.
@type IN_IGNORED: int
@cvar IN_ONLYDIR: only watch the path if it is a directory (new
         in kernel 2.6.15).
@type IN_ONLYDIR: int
@cvar IN_DONT_FOLLOW: don't follow a symlink (new in kernel 2.6.15).
           IN_ONLYDIR we can make sure that we don't watch
           the target of symlinks.
@type IN_DONT_FOLLOW: int
@cvar IN_EXCL_UNLINK: Events are not generated for children after they
           have been unlinked from the watched directory.
           (new in kernel 2.6.36).
@type IN_EXCL_UNLINK: int
@cvar IN_MASK_ADD: add to the mask of an already existing watch (new
          in kernel 2.6.14).
@type IN_MASK_ADD: int
@cvar IN_ISDIR: Event occurred against dir.
@type IN_ISDIR: int
@cvar IN_ONESHOT: Only send event once.
@type IN_ONESHOT: int
@cvar ALL_EVENTS: Alias for considering all of the events.
@type ALL_EVENTS: int

python 3.6的demo

import sys
import os
import pyinotify
WATCH_PATH = '/home/lp/ftp' # 监控目录
if not WATCH_PATH:
  print("The WATCH_PATH setting MUST be set.")
  sys.exit()
else:
  if os.path.exists(WATCH_PATH):
    print('Found watch path: path=%s.' % (WATCH_PATH))
  else:
    print('The watch path NOT exists, watching stop now: path=%s.' % (WATCH_PATH))
    sys.exit()
# 事件回调函数
class OnIOHandler(pyinotify.ProcessEvent):
  # 重写文件写入完成函数
  def process_IN_CLOSE_WRITE(self, event):
    # logging.info("create file: %s " % os.path.join(event.path, event.name))
    # 处理成小图片,然后发送给grpc服务器或者发给kafka
    file_path = os.path.join(event.path, event.name)
    print('文件完成写入',file_path)
  # 重写文件删除函数
  def process_IN_DELETE(self, event):
    print("文件删除: %s " % os.path.join(event.path, event.name))
  # 重写文件改变函数
  def process_IN_MODIFY(self, event):
    print("文件改变: %s " % os.path.join(event.path, event.name))
  # 重写文件创建函数
  def process_IN_CREATE(self, event):
    print("文件创建: %s " % os.path.join(event.path, event.name))
def auto_compile(path='.'):
  wm = pyinotify.WatchManager()
  # mask = pyinotify.EventsCodes.ALL_FLAGS.get('IN_CREATE', 0)
  # mask = pyinotify.EventsCodes.FLAG_COLLECTIONS['OP_FLAGS']['IN_CREATE']               # 监控内容,只监听文件被完成写入
  mask = pyinotify.IN_CREATE | pyinotify.IN_CLOSE_WRITE
  notifier = pyinotify.ThreadedNotifier(wm, OnIOHandler())  # 回调函数
  notifier.start()
  wm.add_watch(path, mask, rec=True, auto_add=True)
  print('Start monitoring %s' % path)
  while True:
    try:
      notifier.process_events()
      if notifier.check_events():
        notifier.read_events()
    except KeyboardInterrupt:
      notifier.stop()
      break
if __name__ == "__main__":
  auto_compile(WATCH_PATH)
  print('monitor close')

watchdog库

支持的监控事件

EVENT_TYPE_MODIFIED: self.on_modified,
EVENT_TYPE_MOVED: self.on_moved,
EVENT_TYPE_CREATED: self.on_created,
EVENT_TYPE_DELETED: self.on_deleted,

需要注意的是,文件改变,也会触发文件夹的改变

python3.6的demo

#! /usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function
import asyncio
import base64
import logging
import os
import shutil
import sys
from datetime import datetime
from watchdog.events import FileSystemEventHandler
from watchdog.observers import Observer
WATCH_PATH = '/home/lp/ftp' # 监控目录
class FileMonitorHandler(FileSystemEventHandler):
 def __init__(self, **kwargs):
  super(FileMonitorHandler, self).__init__(**kwargs)
  # 监控目录 目录下面以device_id为目录存放各自的图片
  self._watch_path = WATCH_PATH
 # 重写文件改变函数,文件改变都会触发文件夹变化
 def on_modified(self, event):
  if not event.is_directory: # 文件改变都会触发文件夹变化
   file_path = event.src_path
   print("文件改变: %s " % file_path)
if __name__ == "__main__":
 event_handler = FileMonitorHandler()
 observer = Observer()
 observer.schedule(event_handler, path=WATCH_PATH, recursive=True) # recursive递归的
 observer.start()
 observer.join()

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对三水点靠木的支持。如果你想了解更多相关内容请查看下面相关链接

Python 相关文章推荐
在Linux上安装Python的Flask框架和创建第一个app实例的教程
Mar 30 Python
python实现用户答题功能
Jan 17 Python
详解Django-auth-ldap 配置方法
Dec 10 Python
Python第三方库h5py_读取mat文件并显示值的方法
Feb 08 Python
Scrapy框架爬取西刺代理网免费高匿代理的实现代码
Feb 22 Python
用python给自己做一款小说阅读器过程详解
Jul 11 Python
基于python实现蓝牙通信代码实例
Nov 19 Python
Flask框架搭建虚拟环境的步骤分析
Dec 21 Python
解决Tensorflow 内存泄露问题
Feb 05 Python
python如何操作mysql
Aug 17 Python
Django框架安装及项目创建过程解析
Sep 14 Python
4种非常实用的python内置数据结构
Apr 28 Python
Python并行分布式框架Celery详解
Oct 15 #Python
对Python 内建函数和保留字详解
Oct 15 #Python
Python 比较文本相似性的方法(difflib,Levenshtein)
Oct 15 #Python
便捷提取python导入包的属性方法
Oct 15 #Python
Django安装配置mysql的方法步骤
Oct 15 #Python
深入理解Django自定义信号(signals)
Oct 15 #Python
使用numba对Python运算加速的方法
Oct 15 #Python
You might like
图书管理程序(三)
2006/10/09 PHP
php全局变量和类配合使用深刻理解
2013/06/05 PHP
解析php中如何直接执行SHELL
2013/06/28 PHP
twig里使用js变量的方法
2016/02/05 PHP
腾讯的ip接口 方便获取当前用户的ip地理位置
2010/11/25 Javascript
各浏览器对click方法的支持差异小结
2011/07/31 Javascript
js确定对象类型方法
2012/03/30 Javascript
使用jquery mobile做幻灯播放效果实现步骤
2013/01/04 Javascript
javascript实现倒计时N秒后网页自动跳转代码
2014/12/11 Javascript
JavaScript Sort 的一个错误用法示例
2015/03/20 Javascript
SpringMVC restful 注解之@RequestBody进行json与object转换
2015/12/10 Javascript
AngularJS 中文API参考手册
2016/07/28 Javascript
使用bootstrap validator的remote验证代码经验分享(推荐)
2016/09/21 Javascript
有关文件上传 非ajax提交 得到后台数据问题
2016/10/12 Javascript
JavaScript的for循环中嵌套一个点击事件的问题解决
2017/03/03 Javascript
以BootStrap Tab为例写一个前端组件
2017/07/25 Javascript
vue兄弟组件传递数据的实例
2018/09/06 Javascript
JS实现放烟花效果
2020/03/10 Javascript
vue2和vue3的v-if与v-for优先级对比学习
2020/10/10 Javascript
[01:00:12]2018DOTA2亚洲邀请赛 4.7 淘汰赛 VP vs LGD 第一场
2018/04/09 DOTA
python通过BF算法实现关键词匹配的方法
2015/03/13 Python
深入浅析ImageMagick命令执行漏洞
2016/10/11 Python
python网络应用开发知识点浅析
2019/05/28 Python
pytorch点乘与叉乘示例讲解
2019/12/27 Python
Python更换pip源方法过程解析
2020/05/19 Python
用Python制作mini翻译器的实现示例
2020/08/17 Python
办理生育手续介绍信
2014/01/14 职场文书
社区道德讲堂实施方案
2014/03/21 职场文书
2014年三万活动总结
2014/04/26 职场文书
员工保密承诺书
2014/05/28 职场文书
庆六一宣传标语
2014/10/08 职场文书
优秀共产党员推荐材料
2014/12/18 职场文书
2015年度合同管理工作总结
2015/05/22 职场文书
css display table 自适应高度、宽度问题的解决
2021/05/07 HTML / CSS
SQL语句多表联合查询的方法示例
2022/04/18 MySQL
JS开发前端团队展示控制器来为成员引流
2022/08/14 Javascript