Surveillance d’un répertoire en python

il est parfois utile de pouvoir surveiller un répertoire en temps réel pour générer des actions par exemple.

Installation

pip install watchdog

Utilisation basique

Objectif surveiller le répertoire sylob

test_watchdog.py

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

if __name__ == "__main__":
    logging.basicConfig(level=logging.INFO,
                        format='%(asctime)s - %(message)s',
                        datefmt='%Y-%m-%d %H:%M:%S')
    path = sys.argv[1] if len(sys.argv) > 1 else '.'
    event_handler = LoggingEventHandler()
    observer = Observer()
    observer.schedule(event_handler, path, recursive=True)
    observer.start()
    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        observer.stop()
    observer.join()

utilisation

>> python test_watchdog.py sylob/
2014-06-19 15:09:23 - Deleted file: C:\Users\f.aoustin\Desktop\sylob\1.txt
2014-06-19 15:09:40 - Created file: C:\Users\f.aoustin\Desktop\sylob\ServiceInformatique.docx
2014-06-19 15:09:40 - Modified file: C:\Users\f.aoustin\Desktop\sylob\ServiceInformatique.docx
2014-06-19 15:09:47 - Moved file: from C:\Users\f.aoustin\Desktop\sylob\ServiceInformatique.docx to C:\Users\f.aoustin\Desktop\sylob\tutu.docx
2014-06-19 15:09:47 - Modified file: C:\Users\f.aoustin\Desktop\sylob\tutu.docx

Utilisation en ligne de commande

watchmedo log --patterns="*.py;*.txt" --ignore-directories --recursive .

lancer une commande à chaque évènement

watchmedo log –patterns=”.py;.txt” –recursive –command=’echo “${watch_src_path}”’ .

Utilisation avancée

Il est possible de créer ses propres handlers

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

class MyHandler(PatternMatchingEventHandler):
    patterns = ["*.xml", "*.lxml"]

    def process(self, event):
        """
        event.event_type
            'modified' | 'created' | 'moved' | 'deleted'
        event.is_directory
            True | False
        event.src_path
            path/to/observed/file
        """
        # the file will be processed there
        print event.src_path, event.event_type  # print now only for degug

    def on_modified(self, event):
        self.process(event)

    def on_created(self, event):
        self.process(event)

if __name__ == '__main__':
    args = sys.argv[1:]
    observer = Observer()
    observer.schedule(MyHandler(), path=args[0] if args else '.')
    observer.start()

    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        observer.stop()

    observer.join()

utilisation

>> python test_watchdog.py sylob/
C:\Users\f.aoustin\Desktop\sylob\log.xml modified
C:\Users\f.aoustin\Desktop\sylob\log.xml modified
C:\Users\f.aoustin\Desktop\sylob\log.xml modified

Note

il existe d’autres action comme on_moved, on_deleted