[Python实战]python-watchdog 超简单例子【开箱可用】【windows】

653 阅读1分钟

python-watchdog

背景

在这里插入图片描述
python第三方库watchdog
看门狗是一款小软件,可以监控文件和目录是否发生变化,watchdog就是一款可以监控文件系统变化的第三方模块,当被监视的区域发生文件或目录的创建,修改,或者删除时,就可以引发特定的事件,我们只需要编写针对这些事件的函数即可处理这些变化。

安装

pip install watchdog

代码

import sys
import time
import logging
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler

#设置打印级别
logging.basicConfig(level=logging.INFO,
                        format='%(asctime)s - %(message)s',
                        datefmt='%Y-%m-%d %H:%M:%S')
#设置观察目录
ROOT_PATH = 'D:\\'

class MyHandler(FileSystemEventHandler):
    def on_modified(self, event):
        logging.info("文件被修改了 %s" % event.src_path)

    def on_created(self, event):
        logging.info("文件被创建了 %s" % event.src_path)

if __name__ == "__main__":
    #path = sys.argv[1] if len(sys.argv) > 1 else '.'
    path = ROOT_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()

运行

python watchdog_example.py

结果

在这里插入图片描述

参考代码

github