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 相关文章推荐
Saltstack快速入门简单汇总
Mar 01 Python
浅谈python字典多键值及重复键值的使用
Nov 04 Python
Python中元组,列表,字典的区别
May 21 Python
Python实现将文本生成二维码的方法示例
Jul 18 Python
python docx 中文字体设置的操作方法
May 08 Python
Vue的el-scrollbar实现自定义滚动
May 29 Python
python3利用tcp实现文件夹远程传输
Jul 28 Python
python使用PIL给图片添加文字生成海报示例
Aug 17 Python
Python3实现爬虫爬取赶集网列表功能【基于request和BeautifulSoup模块】
Dec 05 Python
tf.concat中axis的含义与使用详解
Feb 07 Python
Python使用tkinter制作在线翻译软件
Feb 22 Python
python实现求纯色彩图像的边框
Apr 08 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
jQuery中的RadioButton,input,CheckBox取值赋值实现代码
2014/02/18 PHP
PHP代码优化的53个细节
2014/03/03 PHP
php解析json数据实例
2014/08/19 PHP
php mysql操作mysql_connect连接数据库实例详解
2016/12/26 PHP
基于thinkPHP类的插入数据库操作功能示例
2017/01/06 PHP
php设计模式之享元模式分析【星际争霸游戏案例】
2020/03/23 PHP
Mozilla中显示textarea中选择的文字
2006/09/07 Javascript
让getElementsByName适应IE和firefox的方法
2007/09/24 Javascript
javascript数组快速打乱重排的方法
2014/01/02 Javascript
nodejs命令行参数处理模块commander使用实例
2014/09/17 NodeJs
jQuery中delegate()方法用法实例
2015/01/19 Javascript
深入分析jsonp协议原理
2015/09/26 Javascript
JavaScript笔记之数据属性和存储器属性
2016/03/31 Javascript
jquery validate表单验证插件
2016/09/06 Javascript
浅谈Angular中ngModel的$render
2016/10/24 Javascript
jQuery实现别踩白块儿网页版小游戏
2017/01/18 Javascript
JS实现的走迷宫小游戏完整实例
2017/07/19 Javascript
微信小程序滚动Tab实现左右可滑动切换
2017/08/17 Javascript
vue-resource请求实现http登录拦截或者路由拦截的方法
2018/07/11 Javascript
JS中实现隐藏部分姓名或者电话号码的代码
2018/07/17 Javascript
vue倒计时刷新页面不会从头开始的解决方法
2020/03/03 Javascript
vue中使用echarts的示例
2021/01/03 Vue.js
使用Python的Scrapy框架编写web爬虫的简单示例
2015/04/17 Python
用Python设计一个经典小游戏
2017/05/15 Python
pip安装时ReadTimeoutError的解决方法
2018/06/12 Python
Python将一个CSV文件里的数据追加到另一个CSV文件的方法
2018/07/04 Python
python解包用法详解
2021/02/17 Python
英国和世界各地鲜花速递专家:Arena Flowers
2018/02/10 全球购物
Sasa莎莎海外旗舰店:香港莎莎美妆平台
2018/03/21 全球购物
AJAX的全称是什么
2012/11/06 面试题
代码中finally中的代码会不会执行
2012/02/06 面试题
百日安全生产活动总结
2014/07/05 职场文书
小学阳光体育活动总结
2014/07/05 职场文书
个人先进事迹材料范文
2014/12/29 职场文书
小学运动会通讯稿
2015/07/18 职场文书
Html5通过数据流方式播放视频的实现
2021/04/27 HTML / CSS