全栈工程师开发手册 (作者:栾鹏)
架构系列文章


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 (newin 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 watchthe target of symlinks.
@type IN_DONT_FOLLOW: int
@cvar IN_EXCL_UNLINK: Events are not generated for children after theyhave 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 (newin 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 pyinotifyWATCH_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服务器或者发给kafkafile_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_WRITEnotifier = 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()breakif __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_functionimport asyncio
import base64
import logging
import os
import shutil
import sys
from datetime import datetimefrom watchdog.events import FileSystemEventHandler
from watchdog.observers import ObserverWATCH_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_pathprint("文件改变: %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文件夹,文件监听工具(pyinotify,watchdog)相关推荐

  1. python看门狗(watchdog)、多线程、实现文件夹实时监听、日志输出、备份

    python看门狗(watchdog).多线程.实现文件夹实时监听.日志输出.备份 代码展示 import _thread from watchdog.observers import Observe ...

  2. 制作动态相册的python知识点_动感网页相册 python编写简单文件夹内图片浏览工具...

    不知道大家有没有这样的体验,windows电脑上查看一张gif图,默认就把IE给打开了,还弹出个什么询问项,好麻烦的感觉.所以为了解决自己的这个问题,写了个简单的文件夹内图片浏览工具. 效果图 以E盘 ...

  3. python ftp文件夹文件递归上传推送

    python ftp文件夹文件递归上传推送 posted on 2018-10-16 17:05 秦瑞It行程实录 阅读(...) 评论(...) 编辑 收藏 转载于:https://www.cnbl ...

  4. python 使用sort()函数和正则表达式(lambda)对os.listdir()获取的文件夹文件列表进行重新排序 乱序排序

    # 排序函数,对文件列表进行排序 # 排序函数,对文件列表进行排序(filenames为文件夹文件的文件名的字符串列表) def sort_filenames(filenames):# (1)可以以l ...

  5. Python 创建随机名字的文件夹/文件

    Python 创建随机名字的文件夹/文件 导入库 创建文件名 创建文件 导入库 import random import string import os 创建文件名 dir_name = ''.jo ...

  6. java监听上传文件,Springmvc文件上传监听详解

    spring mvc CommonsMultipartResolver 文件上传监听. /** * 重写 parseRequest方法 监听 */ @Override protected Multip ...

  7. oracle 怎么看监听文件,【学习笔记】Oracle11G关于监听文件位置与监听文件大小限制...

    [学习笔记]Oracle11G关于监听文件位置与监听文件大小限制 时间:2016-11-07 21:21   来源:Oracle研究中心   作者:HTZ   点击: 次 天萃荷净 Oracle研究中 ...

  8. XRename(文件文件夹超级重命名工具)简介

    测试版下载:https://gitee.com/sysdzw/XRename 开放源代码:https://blog.csdn.net/sysdzw/article/details/6213821 gi ...

  9. Python批量修改单个文件夹文件后缀

    今天下载了视频,但是视频格式是.mkv的,唱戏机不支持mkv格式,所以需要将后缀改成.mp4(其他文件格式也可以),由于视频比较多一个一个的更改比较麻烦,所以想到了用python来进行批量修改. 首先 ...

  10. Foldor for Mac(文件夹图标样式修改工具)

    如何修改文件夹图标?推荐Foldor for Mac文件夹图标样式修改工具,多达1000个图标供您选择,支持自定义调色板,需要的朋友快来试试吧! Foldor版安装教程 安装包下载完成后打开,双击.p ...

最新文章

  1. 华为对边缘计算的思考与理解
  2. 神级总结:七种功能强大的聊天机器人平台
  3. 低版本火狐提示HTTPS链接不安全的解决办法
  4. 如何在同一台电脑上同时运行2个tomcat
  5. linux算法设计,嵌入式Linux平台下随机序列算法设计.doc
  6. linux中查看和开放端口
  7. DPDK 跟踪库tracepoint源码实例分析
  8. java 高效加减乘除_java简单加减乘除
  9. 本机未装Oracle数据库时Navicat for Oracle 报错:Cannot create oci environment 原因分析及解决方案
  10. spark算子大全glom_Spark 算子- Value Transformation
  11. php date日期相关函数
  12. 四川大学转专业计算机条件,四川大学转专业需要什么条件
  13. 【OpenCV】58 二值图像分析—寻找最大内接圆
  14. 第844期机器学习日报(2017-01-09)
  15. 微信网页授权多应用多域名使用 oauth2授权
  16. 网页的首屏标准你了解多少?
  17. U-Boot 图形化配置
  18. Semantic UI 之 对话框 modal
  19. 海思3559开发常识储备:相关名词全解
  20. linux命令行测网速

热门文章

  1. 【重磅】亚马逊向第三方开放Echo音箱语音识别技术(附AmazonEcho Dot拆解)
  2. 微信小程序实现语音识别功能
  3. JavaScript-拷贝
  4. 前端elementui el-popover 多行文本换行显示优化
  5. php开发v2ex,继续求 PHP 开发工作
  6. 【java笔记】线程(3):Thread类的常用方法
  7. LeetCode 106/105 从中序和后序/前序遍历序列构造二叉树
  8. MediaExtractor的使用
  9. 前端图片点击按钮加载更多内容_前端开发规范
  10. java面笔试_java笔试手写算法面试题大全含答案