Python使用watchdog实时监测文件或文件夹的更改
更新时间:2026年03月10日 09:22:08 作者:mahuifa
这篇文章主要介绍了如何使用Python的watchdog库来实时监控文件和文件夹的创建、修改、删除操作,实现热重载机制和其他应用场景,需要的朋友可以参考下
1 概述
- python实现实时监控文件的创建、修改、删除操作
- 跟踪文件夹内容的增删改变化
- 可用于文件发生变化时自动触发相应处理逻辑
- 实现热重载机制,如配置文件更新后自动重新加载
基于watchdog 实现;
- watchdog 是一个用于监控文件系统事件的 Python 库,它能够监听文件或目录的变化,如创建、修改、删除和移动等操作。这个库在需要实时响应文件系统变化的场景中非常有用,比如自动构建系统、日志监控、文件同步工具等。
- 主要组件
- Observer:观察者对象,负责监控指定路径的文件系统事件。它会持续运行一个后台线程来监听事件。
- FileSystemEventHandler:事件处理器基类,用户需要继承这个类并重写相应的事件处理方法来定义对特定事件的响应。
- Event:事件对象,代表一个具体的文件系统事件,包含了事件类型和相关文件路径等信息。
典型应用场景
- 开发工具
- 代码编辑器监听源文件变化实现自动刷新
- 构建工具监听源码变更触发重新编译
- 文件同步服务
- 监控本地文件夹变化同步到云端
- 实现文件实时备份功能
- 系统管理
- 监控配置文件变化并动态调整程序行为
- 跟踪重要目录的安全变更记录
2 安装watchdog
- 使用命令行
pip install watchdog进行安装;
pip install watchdog
3 使用示例
监测文件夹更改
import time
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
class MyHandler(FileSystemEventHandler):
def on_modified(self, event):
print(f"文件被修改: {event.src_path}")
def on_created(self, event):
print(f"文件被创建: {event.src_path}")
def on_deleted(self, event):
print(f"文件被删除: {event.src_path}")
if __name__ == "__main__":
path = "./"
event_handler = MyHandler()
observer = Observer()
observer.schedule(event_handler, path, recursive=True)
observer.start()
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
observer.stop()
observer.join()
监测指定文件更改
import time
import os
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
class MyHandler(FileSystemEventHandler):
def __init__(self, target_file):
self.target_file = os.path.abspath(target_file)
self.last_modified = 0
def dispatch(self, event):
if os.path.abspath(event.src_path) == self.target_file:
super().dispatch(event)
def on_modified(self, event):
now = time.time()
# 1秒内只响应一次
if now - self.last_modified > 1:
print(f"文件被修改: {event.src_path}")
self.last_modified = now
def on_created(self, event):
print(f"文件被创建: {event.src_path}")
def on_deleted(self, event):
print(f"文件被删除: {event.src_path}")
if __name__ == "__main__":
target_file = "test.txt"
path = os.path.dirname(os.path.abspath(target_file)) or "."
event_handler = MyHandler(target_file)
observer = Observer()
observer.schedule(event_handler, path, recursive=False)
observer.start()
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
observer.stop()
observer.join()
- 因为许多编辑器(如 VS Code、Notepad++ 等)在保存文件时,可能会执行多步操作(如写入临时文件、替换原文件、修改元数据等),导致 watchdog 检测到多次文件系统事件
- 事件去抖动(防抖):在短时间内多次事件只处理一次。
到此这篇关于Python使用watchdog实时监测文件或文件夹更改的文章就介绍到这了,更多相关Python watchdog监测文件/文件夹更改内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
Django 事务transaction.atomic()的使用方法
本文主要介绍了Django 事务transaction.atomic()的使用方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧2025-12-12
PyTorch中tensor.backward()函数的详细介绍及功能实现
backward() 函数是PyTorch框架中自动求梯度功能的一部分,它负责执行反向传播算法以计算模型参数的梯度,这篇文章主要介绍了PyTorch中tensor.backward()函数的详细介绍,需要的朋友可以参考下2024-02-02


最新评论