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中字符串类型json操作的注意事项
May 02 Python
Python实现自动登录百度空间的方法
Jun 10 Python
详解python中 os._exit() 和 sys.exit(), exit(0)和exit(1) 的用法和区别
Jun 23 Python
python中numpy包使用教程之数组和相关操作详解
Jul 30 Python
Python简单读取json文件功能示例
Nov 30 Python
python列表生成式与列表生成器的使用
Feb 23 Python
解决Mac下首次安装pycharm无project interpreter的问题
Oct 29 Python
python实现RabbitMQ的消息队列的示例代码
Nov 08 Python
vim自动补全插件YouCompleteMe(YCM)安装过程解析
Oct 21 Python
pycharm下pyqt4安装及环境配置的教程
Apr 24 Python
matplotlib基础绘图命令之errorbar的使用
Aug 13 Python
用Python创建简易网站图文教程
Jun 11 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
基于wordpress主题制作的具体实现步骤
2013/05/10 PHP
PHPExcel简单读取excel文件示例
2016/05/26 PHP
thinkPHP中U方法加密传递参数功能示例
2018/05/29 PHP
PHP示例演示发送邮件给某个邮箱
2019/04/03 PHP
accesskey 提交
2006/06/26 Javascript
JavaScript的parseInt 进制问题
2009/05/07 Javascript
JS 两个字符串时间的天数差计算
2013/08/25 Javascript
JavaScript使用setInterval()函数实现简单轮询操作的方法
2015/02/02 Javascript
javascript 闭包详解
2015/07/02 Javascript
JavaScript实现数值自动增加动画
2017/12/28 Javascript
Vue-Cli项目优化操作的实现
2019/10/27 Javascript
在vue中利用全局路由钩子给url统一添加公共参数的例子
2019/11/01 Javascript
JavaScript中CreateTextFile函数
2020/08/30 Javascript
[01:20]2018DOTA2亚洲邀请赛总决赛战队Mineski晋级之路
2018/04/07 DOTA
python列表去重的二种方法
2014/02/14 Python
Python进行数据提取的方法总结
2016/08/22 Python
python调用xlsxwriter创建xlsx的方法
2018/05/03 Python
详解python读取和输出到txt
2019/03/29 Python
python3+PyQt5 使用三种不同的简便项窗口部件显示数据的方法
2019/06/17 Python
django连接oracle时setting 配置方法
2019/08/29 Python
python3 配置logging日志类的操作
2020/04/08 Python
PyPDF2读取PDF文件内容保存到本地TXT实例
2020/05/12 Python
python根据字典的键来删除元素的方法
2020/08/16 Python
CSS3 新增选择器的实例
2019/11/13 HTML / CSS
英国知名的皮手套品牌:Dents
2016/11/13 全球购物
Tomcat Mysql datasource数据源配置
2015/12/28 面试题
物流专业毕业生推荐信范文
2013/11/18 职场文书
党风廉政承诺书
2014/03/27 职场文书
春风行动实施方案
2014/03/28 职场文书
保密工作目标责任书
2014/07/28 职场文书
先进事迹演讲稿
2014/09/01 职场文书
教书育人演讲稿
2014/09/11 职场文书
咖啡厅商业计划书
2014/09/15 职场文书
世界文化遗产导游词
2015/02/13 职场文书
2016年感恩母亲节活动总结
2016/04/01 职场文书
如何在C++中调用Python
2021/05/21 Python