文章目录

  • 简介
  • 安装
  • 初试
  • 重定向到日志中
  • Handler类型
  • 命令行工具
  • 动态日志监控
  • 遇到的坑
  • 参考文献

简介

Watchdog是一款用于监控文件系统事件的Python库,对不同平台的事件进行了封装。

Watchdog优先使用底层原生API,其次再通过轮询磁盘实现监控,目前支持以下操作系统:

  • Windows:ReadDirectoryChangesW
  • Linux 2.6+:inotify
  • Mac OS X:kqueue 或 FSEvents
  • BSD Unix variants:kqueue

仅支持Python 3.5+

安装

pip install watchdog

初试

import time
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandlerclass MyHandler(FileSystemEventHandler):def on_any_event(self, event):print(event.event_type, event.src_path)event_handler = MyHandler()
observer = Observer()
observer.schedule(event_handler, path='.', recursive=False)
observer.start()
try:while True:time.sleep(0.1)
except KeyboardInterrupt:observer.stop()
observer.join()

运行后,执行以下操作

  1. 新建文本文档
  2. 改名为 a.txt
  3. 输入内容 Hello World! 并保存
  4. 删除 a.txt

效果:

created .\a.txt
modified .\a.txt~
modified .\a.txt
moved .\a.txt
deleted .\b.txt

退出:Ctrl+C

PS:

  • PyCharm直接操作可能有延迟

重定向到日志中

输出重定向为logging日志中

import sys
import time
import logging
from watchdog.observers import Observer
from watchdog.events import LoggingEventHandlerlogging.basicConfig(level=logging.INFO,format='%(asctime)s - %(message)s',datefmt='%Y-%m-%d %H:%M:%S')
path = sys.argv[1] if len(sys.argv) > 1 else '.'
event_handler = LoggingEventHandler()
observer = Observer()
observer.schedule(event_handler, path, recursive=True)
observer.start()
try:while True:time.sleep(0.1)
finally:observer.stop()observer.join()

测试

import os
import timen = 0
src = 'a.txt'
dst = 'b.txt'
if os.path.exists(src):os.remove(src)
if os.path.exists(dst):os.remove(dst)
while True:n += 1with open(src, 'w') as f:print(f.write('Hello World!\n'))time.sleep(0.5)if n == 2:os.rename(src, dst)if n == 5:os.remove(src)os.remove(dst)n = 0

输出

2020-12-02 15:52:43 - Created file: .\a.txt
2020-12-02 15:52:43 - Modified file: .\a.txt
2020-12-02 15:52:44 - Modified file: .\a.txt
2020-12-02 15:52:44 - Modified file: .\a.txt
2020-12-02 15:52:45 - Modified file: .\a.txt
2020-12-02 15:52:45 - Modified file: .\a.txt
2020-12-02 15:52:46 - Deleted file: .\a.txt
2020-12-02 15:52:46 - Deleted file: .\b.txt

Handler类型

类型 功能
FileSystemEventHandler 文件
PatternMatchingEventHandler 模式匹配文件
RegexMatchingEventHandler 正则匹配文件
LoggingEventHandler 记录日志

命令行工具

安装

pip install watchdog[watchmedo]

查看命令

watchmedo --help

动态日志监控

思路:

  1. 打开文件将流位置改到末尾并记录当前位置
  2. watchdog监控
  3. 一旦触发文件修改,将流位置改到末尾,记录当前位置
  4. 根据步骤1和步骤3的位置获取新增片段
  5. 解析新增片段

推荐阅读

  1. Python一行代码实现Linux的tail
  2. logPatrol GitHub

不断写时间

import time
import logginglogging.basicConfig(level=logging.INFO, format='%(asctime)s', datefmt='%H:%M:%S')
logger = logging.getLogger()
logger.setLevel(logging.INFO)
fileHandler = logging.FileHandler('test.log', mode='a+')
formatter = logging.Formatter('%(asctime)s', datefmt='%H:%M:%S')
fileHandler.setFormatter(formatter)
logger.addHandler(fileHandler)while True:logger.info('')time.sleep(1)

监控变化并输出内容

import os
import time
from watchdog.observers import Observer
from watchdog.events import PatternMatchingEventHandlerf = open('test.log', 'rb')
f.seek(0, os.SEEK_END)  # 将流位置改为末尾
last_position = f.tell()  # 上次的流末尾位置
f.close()class MyHandler(PatternMatchingEventHandler):def __init__(self, patterns=['*.log'], ignore_patterns=None, ignore_directories=False, case_sensitive=False):super().__init__(patterns, ignore_patterns, ignore_directories, case_sensitive)def on_modified(self, event):global last_positionf = open(event.src_path, 'rb')f.seek(0, os.SEEK_END)now_position = f.tell()if now_position == last_position:returnread_bytes = now_position - last_position  # 新增内容f.seek(last_position, os.SEEK_SET)  # 光标从开头移动data = f.read(read_bytes).decode('utf-8')last_position = now_positionf.close()print(data)if __name__ == '__main__':print('正在监控')event_handler = MyHandler()observer = Observer()observer.schedule(event_handler, path='.', recursive=False)observer.start()try:while True:time.sleep(0.1)except KeyboardInterrupt:observer.stop()observer.join()

推荐阅读:

  1. io — 处理流的核心工具

遇到的坑

1. Windows与Linux的差异

Windows下打开一个文件后不断写入,只要没有保存的动作,都不会触发 on_modified 事件。

Linux写入即触发。

参考文献

  1. Watchdog GitHub
  2. Watchdog Documentation
  3. python中文件变化监控-watchdog
  4. watchdog for Python 实例
  5. Python十大开发技巧

Python Watchdog——监控文件系统事件相关推荐

  1. linux inotify 监控文件系统事件

    1. Inotify 机制概述 1.1. Inotify 介绍 在日常的运维过程中,经常需要备份某些文件,或者对系统的某些文件进行监控,比如重要的配置文件等.如果需要作到实时同步或者监控,就需要使用内 ...

  2. python watchdog 同时检测到多个事件_python中watchdog文件监控与检测上传功能

    引言 上一篇介绍完了观察者模式的原理,本篇想就此再介绍一个小应用,虽然我也就玩了一下午,是当时看observer正好找到的,以及还有Django-observer,但Django很久没用了,所以提下这 ...

  3. Python Inotify 监视LINUX文件系统事件

    Inotify 可以监视的LINUX文件系统事件包括: --IN_ACCESS,即文件被访问  --IN_MODIFY,文件被write  --IN_ATTRIB,文件属性被修改,如chmod.cho ...

  4. linux流行开源监控框架,Inotify: 高效、实时的Linux文件系统事件监控框架

    概要 - 为什么需要监控文件系统? 在日常工作中,人们往往需要知道在某些文件(夹)上都有那些变化,比如: 通知配置文件的改变 跟踪某些关键的系统文件的变化 监控某个分区磁盘的整体使用情况 系统崩溃时进 ...

  5. python watchdog占用,python基于watchdog库全自动化监控目录文件

    楔子 有些时候我们需要对一个目录进行监控,检测其内部是否有文件的新增.删除.以及每个文件的内容是否发生变化,这个时候如果是你的话,你会选择怎么做呢? 显然也是一个比较麻烦的工作,倒不是说难,主要是比较 ...

  6. inotify之文件系统事件监控使用入门

    inotify是linux文件系统事件监控机制,功能强大,控制简单,可以实现很多有用的功能.如:当一个文件被访问.打开.关闭.移动.删除等等时做一些处理.此功能需要内核支持,从kernel 2.6.1 ...

  7. python watchdog的使用_python watchdog监控文件修改

    概述 watchdog用来监控指定目录/文件的变化,如添加删除文件或目录.修改文件内容.重命名文件或目录等,每种变化都会产生一个事件,且有一个特定的事件类与之对应,然后再通过事件处理类来处理对应的事件 ...

  8. linux 高效的文件系统事件监控 内核级解析方案 inotify

    转载 http://www.lvtao.net/config/inotify.html linux 高效的文件系统事件监控 内核级解析方案 inotify 安装inotify-tools (http: ...

  9. inotify 实时的Linux文件系统事件监控

    标签:inotifywait 原创作品,允许转载,转载时请务必以超链接形式标明文章 原始出处 .作者信息和本声明.否则将追究法律责任.http://cqfish.blog.51cto.com/6222 ...

最新文章

  1. Oracle数据库分组函数详解
  2. 电脑不能打字_宝妈、学生、上班族手机兼职——打字录入
  3. python 异常处理模块_扩展Python模块系列(五)----异常和错误处理
  4. php微信h5支付对接流程,微信H5支付接口开发的流程与常见问题
  5. Mujoco的关节与外力和驱动器
  6. 直击进博会 | 强生、默沙东、史赛克、雅培、丹纳赫、罗氏、拜耳等医药巨头带来哪些新产品、新技术?...
  7. R语言_缺失值NA的处理
  8. 腾讯云点播视频播放器使用步骤 uniapp
  9. 面对对象原则:高内聚、低耦合
  10. 又是一江春水自东流!
  11. 【故事】《阿里云的这群疯子》:深度好文阅读推荐
  12. 在keil中使用bdata型可位寻址全局变量
  13. matplotlib生成没有留白的图片
  14. Java项目:jsp+servlet图书管理系统
  15. MyBatis 多对多关联映射
  16. linux_时区修改
  17. PTA L1-040:最萌情侣身高差 (python)
  18. java闪光的星星_基于JavaScript实现飘落星星特效
  19. windows下上传ipa文件到开发者中心的方法
  20. 基于JAVA的医院门诊信息管理系统

热门文章

  1. PTA L2-16愿天下有情人都是失散多年的兄妹(25分)(python)
  2. Activity快速转换为Diglog,面试题bug的生命周期
  3. 怎么把Mesh转为SDF
  4. 入门学习爬取贴吧图片(附完整代码),2021/1/27有效
  5. 鸿蒙空间命运法则,鸿蒙法则_仙域官网_跟我玩(Game5)游戏平台
  6. Tracert命令详解,路由跟踪命令tracert命令怎么用?网络管理员的法宝,新睿云给您详解
  7. 简述彭罗斯近年一些公开讲堂内容的物理意义
  8. 计算机控制系统席爱民4,计算机控制系统(席爱民).pdf
  9. 我再copy回来。中海真是有心人。
  10. 相机标定python