Python每日一练:watchdog文件目录事件监控

监控指定目录下的文件或文件夹的变动

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

首先,你需要安装watchdog

pip install watchdog
from watchdog.observers import Observer  
from watchdog.events import *  
import time  

class FileEventHandler(FileSystemEventHandler):  
    def __init__(self):  
        FileSystemEventHandler.__init__(self)  

    def on_moved(self, event):  
        if event.is_directory:  
            print("directory moved from {0} to {1}".format(event.src_path,event.dest_path))  
        else:  
            print("file moved from {0} to {1}".format(event.src_path,event.dest_path))  

    def on_created(self, event):  
        if event.is_directory:  
            print("directory created:{0}".format(event.src_path))  
        else:  
            print("file created:{0}".format(event.src_path))  

    def on_deleted(self, event):  
        if event.is_directory:  
            print("directory deleted:{0}".format(event.src_path))  
        else:  
            print("file deleted:{0}".format(event.src_path))  

    def on_modified(self, event):  
        if event.is_directory:  
            print("directory modified:{0}".format(event.src_path))  
        else:  
            print("file modified:{0}".format(event.src_path))  

if __name__ == "__main__":  
    observer = Observer()  
    event_handler = FileEventHandler()  
    observer.schedule(event_handler, "/home/tester/testdir", True)  
    observer.start()  
    observer.join()  
    print('end...')