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 相关文章推荐
Python base64编码解码实例
Jun 21 Python
Python爬取国外天气预报网站的方法
Jul 10 Python
Python中绑定与未绑定的类方法用法分析
Apr 29 Python
Python简单获取自身外网IP的方法
Sep 18 Python
Python Queue模块详细介绍及实例
Dec 27 Python
Python爬虫包BeautifulSoup学习实例(五)
Jun 17 Python
pandas 快速处理 date_time 日期格式方法
Nov 12 Python
python实现简单聊天室功能 可以私聊
Jul 12 Python
tensorflow 利用expand_dims和squeeze扩展和压缩tensor维度方式
Feb 07 Python
pytorch VGG11识别cifar10数据集(训练+预测单张输入图片操作)
Jun 24 Python
Python实现打包成库供别的模块调用
Jul 13 Python
Python判断字符串是否为合法标示符操作
Sep 03 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
《雄兵连》《烈阳天道》真的来了
2020/07/13 国漫
PHP逐行输出(ob_flush与flush的组合)
2012/02/04 PHP
php中将数组转成字符串并保存到数据库中的函数代码
2013/09/29 PHP
json的前台操作和后台操作实现代码
2012/01/20 Javascript
javascript类型转换使用方法
2014/02/08 Javascript
js控制网页前进和后退的方法
2015/06/08 Javascript
JQuery插入DOM节点的方法
2015/06/11 Javascript
分享15个大家都熟知的jquery小技巧
2015/12/02 Javascript
jQuery防止重复绑定事件的解决方法
2016/05/14 Javascript
JavaScript数据操作_浅谈原始值和引用值的操作本质
2016/08/23 Javascript
Angularjs的Controller间通信机制实例分析
2016/11/07 Javascript
解析如何利用iframe标签以及js制作时钟
2016/12/08 Javascript
js仿淘宝商品放大预览功能
2017/03/15 Javascript
解决AngualrJS页面刷新导致异常显示问题
2017/04/20 Javascript
js判断用户是输入的地址请求的路径(实例讲解)
2017/07/18 Javascript
JS实现点击链接切换显示隐藏内容的方法
2017/10/19 Javascript
webpack多入口文件页面打包配置详解
2018/01/09 Javascript
详解在vue-test-utils中mock全局对象
2018/11/07 Javascript
javascriptvoid(0)含义以及与"#"的区别讲解
2019/01/19 Javascript
Echarts.js无法引入问题解决方案
2020/10/30 Javascript
[01:11:32]VG vs FNATIC 2019国际邀请赛小组赛 BO2 第二场 8.15
2019/08/17 DOTA
举例讲解如何在Python编程中进行迭代和遍历
2016/01/19 Python
Python进行数据提取的方法总结
2016/08/22 Python
Django自定义用户认证示例详解
2018/03/14 Python
python 编码规范整理
2018/05/05 Python
python 使用 requests 模块发送http请求 的方法
2018/12/09 Python
TensorFlow的reshape操作 tf.reshape的实现
2020/04/19 Python
Django:使用filter的pk进行多值查询操作
2020/07/15 Python
详解如何在pyqt中通过OpenCV实现对窗口的透视变换
2020/09/20 Python
Opencv 图片的OCR识别的实战示例
2021/03/02 Python
CSS3混合模式mix-blend-mode/background-blend-mode简介
2018/03/15 HTML / CSS
入党积极分子评语
2014/05/04 职场文书
安全生产知识竞赛活动总结
2014/07/07 职场文书
《浅水洼里的小鱼》教学反思
2016/02/16 职场文书
如何制定销售人员薪酬制度?
2019/07/09 职场文书
Python识别花卉种类鉴定网络热门植物并自动整理分类
2022/04/08 Python