python

关注公众号 jb51net

关闭
首页 > 脚本专栏 > python > Python watchdog监测文件/文件夹更改

Python使用watchdog实时监测文件或文件夹的更改

作者:mahuifa

这篇文章主要介绍了如何使用Python的watchdog库来实时监控文件和文件夹的创建、修改、删除操作,实现热重载机制和其他应用场景,需要的朋友可以参考下

1 概述

基于watchdog 实现;

典型应用场景

  1. 开发工具
    • 代码编辑器监听源文件变化实现自动刷新
    • 构建工具监听源码变更触发重新编译
  2. 文件同步服务
    • 监控本地文件夹变化同步到云端
    • 实现文件实时备份功能
  3. 系统管理
    • 监控配置文件变化并动态调整程序行为
    • 跟踪重要目录的安全变更记录

2 安装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()

到此这篇关于Python使用watchdog实时监测文件或文件夹更改的文章就介绍到这了,更多相关Python watchdog监测文件/文件夹更改内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文