Watchdog để theo dõi thay đổi file

Cài đặt

pip install watchdog

Chương trình

#!/usr/bin/env python3
​
from __future__ import print_function
​
import sys
import time
import json
import subprocess
from watchdog.observers import Observer
from watchdog.events import PatternMatchingEventHandler
from watchdog.events import RegexMatchingEventHandler
​
class FileWatchHandler(PatternMatchingEventHandler):
    def __init__(self, command, patterns):
        super(FileWatchHandler, self).__init__(patterns=patterns)
        self.command = command
​
    def _run_command(self):
        subprocess.call([self.command, ])
​
    def on_moved(self, event):
        self._run_command()
        print("event_type = ", event.event_type)
        print("src_path = ", event.src_path)
        print("dest_path = ", event.dest_path)
        
    def on_created(self, event):
        self._run_command()
        print("event_type = ", event.event_type)
        print("src_path = ", event.src_path)
​
    def on_deleted(self, event):
        self._run_command()
        print("event_type = ", event.event_type)
        print("src_path = ", event.src_path)
        
    def on_modified(self, event):
        self._run_command()
        print("event_type = ", event.event_type)
        print("src_path = ", event.src_path)
​
def watch(path, command, extension):
    event_handler = FileWatchHandler(command, ["*"+extension])
    observer = Observer()
    observer.schedule(event_handler, path, recursive=True)
    observer.start()
    
    try:
        while True:
            time.sleep(0.0001)
    except KeyboardInterrupt:
        observer.stop()
    observer.join()
    
if __name__ == "__main__":
    if 4 > len(sys.argv):
        print("Usage:", sys.argv[0], "[dir_to_watch] [command] [extension]")
    else:
        watch(sys.argv[1], sys.argv[2], sys.argv[3])

Cách dụng

Đối với folder <directory_to_watch>, file có đuôi là <extension> thay đổi, tạo mới, xoá thì sẽ thực hiện dòng lệnh <command>

python dirwatch.py <directory_to_watch> <command> <extension>
Share

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *