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设计模式之观察者模式实例
Apr 26 Python
浅析Git版本控制器使用
Dec 10 Python
Python冲顶大会 快来答题!
Jan 17 Python
简单实现python数独游戏
Mar 30 Python
Linux系统(CentOS)下python2.7.10安装
Sep 26 Python
解析Python3中的Import
Oct 13 Python
python的time模块和datetime模块实例解析
Nov 29 Python
Python:type、object、class与内置类型实例
Dec 25 Python
Python时间差中seconds和total_seconds的区别详解
Dec 26 Python
django model通过字典更新数据实例
Apr 01 Python
python函数指定默认值的实例讲解
Mar 29 Python
python for循环赋值问题
Jun 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
Oracle 常见问题解答
2006/10/09 PHP
PHP自动更新新闻DIY
2006/10/09 PHP
php下通过伪造http头破解防盗链的代码
2010/07/03 PHP
zend framework多模块多布局配置
2011/02/26 PHP
PHP+Mysql+jQuery查询和列表框选择操作实例讲解
2015/10/22 PHP
php中array_slice和array_splice函数解析
2016/10/18 PHP
laravel自定义分页效果
2017/07/23 PHP
解决 FireFox 下[使用event很麻烦] 的问题.
2006/08/22 Javascript
jQueryUI如何自定义组件实现代码
2010/11/14 Javascript
解读JavaScript代码 var ie = !-[1,] 最短的IE判定代码
2011/05/28 Javascript
基于jquery的大众点评,分类导航实现代码
2011/08/23 Javascript
javascript图像处理—仿射变换深度理解
2013/01/16 Javascript
jQuery网页版打砖块小游戏源码分享
2015/08/20 Javascript
浅谈$_FILES数组为空的原因
2017/02/16 Javascript
ES6新特性四:变量的解构赋值实例
2017/04/21 Javascript
浅谈ECMAScript6新特性之let、const
2017/08/02 Javascript
详细分析JS函数去抖和节流
2017/12/05 Javascript
vue项目刷新当前页面的三种方法
2018/12/04 Javascript
Angular中使用ng-zorro图标库部分图标不能正常显示问题
2019/04/22 Javascript
Vue 通过公共字段,拼接两个对象数组的实例
2019/11/07 Javascript
python读文件保存到字典,修改字典并写入新文件的实例
2018/04/23 Python
python 获取当天凌晨零点的时间戳方法
2018/05/22 Python
创建pycharm的自定义python模板方法
2018/05/23 Python
机器学习之KNN算法原理及Python实现方法详解
2018/07/09 Python
Python常见数据结构之栈与队列用法示例
2019/01/14 Python
Python创建字典的八种方式
2019/02/27 Python
在Python中如何传递任意数量的实参的示例代码
2019/03/21 Python
Flask框架模板继承实现方法分析
2019/07/31 Python
Python对象的属性访问过程详解
2020/03/05 Python
python获取响应某个字段值的3种实现方法
2020/04/30 Python
Python改变对象的字符串显示的方法
2020/08/01 Python
Python利用pip安装tar.gz格式的离线资源包
2020/09/14 Python
CSS3 3D酷炫立方体变换动画的实现
2019/03/26 HTML / CSS
2015年学校禁毒工作总结
2015/05/27 职场文书
幼儿园六一主持词
2015/06/30 职场文书
MySQL EXPLAIN输出列的详细解释
2021/05/12 MySQL