简介:watchdog 是一个用于监控文件系统变化的 Python 模块。它能够检测文件和目录的创建、修改、删除等事件,并能实时触发相应的操作。这个模块适合用于自动化构建工具、文件同步服务和其他需要文件监控的应用。
历史攻略:
locust2.0+教程:小试牛刀 - 利用辅助监控工具查看性能压测资源开销
一、watchdog 模块的基本特性:
-
实时监控:能够实时捕获文件系统的变化事件。
-
跨平台支持:在 Windows、Linux 和 macOS 上均可使用。
-
灵活的事件处理:支持自定义事件处理程序,允许开发者根据需要执行相应操作。
二、安装:
pip install watchdog
三、基本用法:
- 创建事件处理程序:通过继承 FileSystemEventHandler 类,定义要处理的文件变化事件。
- 设置观察者:使用 Observer 类来监控指定的目录。
常用事件:
on_modified: 当文件被修改时触发。
on_created: 当文件被创建时触发。
on_deleted: 当文件被删除时触发.
on_moved: 当文件被移动时触发。
四、示例代码:
# -*- coding: utf-8 -*-
# time: 2024/10/02 10:02
# file: watchdog_demo.py
# author: tom
# 微信公众号: 玩转测试开发
import time
import datetime
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
# 自定义事件处理程序
class MyEventHandler(FileSystemEventHandler):
def on_modified(self, event):
print(f"File modified: {event.src_path} , {datetime.datetime.now()}")
def on_created(self, event):
print(f"File created: {event.src_path} , {datetime.datetime.now()}")
def on_deleted(self, event):
print(f"File deleted: {event.src_path} , {datetime.datetime.now()}")
def on_moved(self, event):
print(f"File moved: {event.src_path} to {event.dest_path} , {datetime.datetime.now()}")
# 设置观察者
def start_watching(path):
event_handler = MyEventHandler()
observer = Observer()
observer.schedule(event_handler, path, recursive=True)
observer.start()
print(f"Monitoring changes in: {path} , {datetime.datetime.now()}")
try:
while True:
time.sleep(1) # 保持程序运行
except KeyboardInterrupt:
observer.stop()
observer.join()
if __name__ == "__main__":
watch_path = "." # 监控当前目录
start_watching(watch_path)
五、运行结果参考:
Monitoring changes in: . , 2024-10-02 00:44:12.057906
File moved: .\tom2.py to .\tom.py , 2024-10-02 00:44:28.136278
File created: .\tools , 2024-10-02 00:44:38.829325
File created: .\tools\__init__.py , 2024-10-02 00:44:38.831324
File created: .\tools\__init__.py~ , 2024-10-02 00:44:38.834328
File modified: .\tools\__init__.py~ , 2024-10-02 00:44:38.834328
File modified: .\tools\__init__.py , 2024-10-02 00:44:38.837327
File modified: .\tools\__init__.py , 2024-10-02 00:44:38.844319
File deleted: .\tools\__init__.py~ , 2024-10-02 00:44:38.844319
File deleted: .\tools\__init__.py , 2024-10-02 00:44:46.392958
File modified: .\tools , 2024-10-02 00:44:46.392958
File deleted: .\tools , 2024-10-02 00:44:46.392958
File created: .\a_dir , 2024-10-02 00:44:57.729338
File deleted: .\a_dir , 2024-10-02 00:45:04.621320
File created: .\001\a_dir , 2024-10-02 00:45:04.621320
File modified: .\001 , 2024-10-02 00:45:04.621320
File modified: .\001\a_dir , 2024-10-02 00:45:04.621320
六、说明解析
自定义事件处理程序
该示例通过继承 FileSystemEventHandler 类创建了一个自定义事件处理程序 MyEventHandler,并实现了四个事件处理方法。这些方法会在文件发生变化时被调用,输出相关信息。
设置观察者
在 start_watching 函数中,创建了一个 Observer 实例并将自定义事件处理程序与指定的监控路径关联。调用 observer.start() 开始监控,并通过 while 循环保持程序运行。
七、小结
watchdog 模块是监控文件变化的强大工具,通过实时捕获文件系统的变化事件,开发者可以在自动化构建、文件同步等场景中提高工作效率。掌握该模块的基本用法,可以帮助开发者更好地管理文件和目录,提升应用的响应能力。