Watchdog is quite useful for file monitoring

Hitting win32api is nonsense, and I wanted to write it easily, so when I was searching with pypi, I found out watchdog.

Below is the code that "notifies you when three files * .jpg, * .png, * .txt are created / edited / deleted".

watchdog_example.py


#!/usr/bin/env python
# -*- coding: utf-8 -*-

import time
import os

from watchdog.events import FileSystemEventHandler
from watchdog.observers import Observer

BASEDIR = os.path.abspath(os.path.dirname(__file__))

def getext(filename):
    return os.path.splitext(filename)[-1].lower()

class ChangeHandler(FileSystemEventHandler):

    def on_created(self, event):
        if event.is_directory:
            return
        if getext(event.src_path) in ('.jpg','.png','.txt'):
            print('%s has been created.' % event.src_path)

    def on_modified(self, event):
        if event.is_directory:
            return
        if getext(event.src_path) in ('.jpg','.png','.txt'):
            print('%s has been modified.' % event.src_path)

    def on_deleted(self, event):
        if event.is_directory:
            return
        if getext(event.src_path) in ('.jpg','.png','.txt'):
            print('%s has been deleted.' % event.src_path)

if __name__ in '__main__':
    while 1:
        event_handler = ChangeHandler()
        observer = Observer()
        observer.schedule(event_handler,BASEDIR,recursive=True)
        observer.start()
        try:
            while True:
                time.sleep(1)
        except KeyboardInterrupt:
            observer.stop()
        observer.join()

I think you should write the process you want to execute in on_created, on_modified, on_deleted.

For example, you can automate it by using watchdog without editing doc and making make html by yourself.

The only thing I was worried about when I touched it was that if it was on_any_event when creating the file, it would be executed twice.

As you can see by using this code, it seems that the create event is executed in the order of on_created, on_modified.

I don't know what's inside the OS, so it's just an estimate.

Recommended Posts

Watchdog is quite useful for file monitoring
Python-dotfiles is useful for managing dotfiles
Zope.interface is useful for practicing Hexagonal Architecture
This is your choice for env file management!
A scene where GPU is useful for deep learning?
What is Linux for?