Claude Code for watchdog: Python File System Monitoring — Claude Skills 360 Blog
Blog / AI / Claude Code for watchdog: Python File System Monitoring
AI

Claude Code for watchdog: Python File System Monitoring

Published: January 23, 2028
Read time: 5 min read
By: Claude Skills 360

watchdog monitors file system events in Python. pip install watchdog. Observer: from watchdog.observers import Observer. Handler: from watchdog.events import FileSystemEventHandler. handler = FileSystemEventHandler(). observer = Observer(); observer.schedule(handler, path=".", recursive=True); observer.start(). Subclass: class MyHandler(FileSystemEventHandler): def on_modified(self, event): print(event.src_path). Events: on_created, on_modified, on_deleted, on_moved. Event attrs: event.src_path, event.dest_path (moved), event.is_directory. Pattern: from watchdog.events import PatternMatchingEventHandler. PatternMatchingEventHandler(patterns=["*.py","*.json"], ignore_patterns=["*.pyc"], ignore_directories=True, case_sensitive=False). Regex: from watchdog.events import RegexMatchingEventHandler. RegexMatchingEventHandler(regexes=[r".*\.py$"], ignore_regexes=[r".*__pycache__.*"]). Observer lifecycle: observer.start(). observer.stop(); observer.join(). Multiple watches: observer.schedule(h1, "src/", recursive=True). observer.schedule(h2, "config/", recursive=False). observer.unschedule(watch). observer.unschedule_all(). Non-blocking: Observer runs in a daemon thread — main thread stays free. Stop: observer.is_alive(). Debounce: use threading.Timer or time.time() delta to collapse rapid events. inotify backend: Linux uses inotify by default — efficient. Polling: from watchdog.observers.polling import PollingObserver — for networked/NFS paths. PollingObserver(timeout=1). Claude Code generates watchdog handlers, debounced file watchers, and auto-reload pipelines.

CLAUDE.md for watchdog

## watchdog Stack
- Version: watchdog >= 4.0 | pip install watchdog
- Observer: observer = Observer(); observer.schedule(handler, path, recursive=True)
- Handler: class H(FileSystemEventHandler): on_created/on_modified/on_deleted/on_moved
- Pattern: PatternMatchingEventHandler(patterns=["*.py"], ignore_directories=True)
- Debounce: collapse rapid on_modified events with threading.Timer(delay, callback)
- Threading: Observer is a daemon thread — call observer.stop(); observer.join() to exit
- Polling: PollingObserver for network mounts where inotify is unavailable

watchdog File System Monitoring Pipeline

# app/file_watcher.py — watchdog event handlers, debouncing, and auto-reload
from __future__ import annotations

import logging
import threading
import time
from collections import defaultdict
from pathlib import Path
from queue import Empty, Queue
from typing import Callable

from watchdog.events import (
    FileCreatedEvent,
    FileDeletedEvent,
    FileModifiedEvent,
    FileMovedEvent,
    FileSystemEvent,
    FileSystemEventHandler,
    PatternMatchingEventHandler,
    RegexMatchingEventHandler,
)
from watchdog.observers import Observer
from watchdog.observers.polling import PollingObserver

log = logging.getLogger(__name__)


# ─────────────────────────────────────────────────────────────────────────────
# 1. Basic handler — log all events
# ─────────────────────────────────────────────────────────────────────────────

class LoggingHandler(FileSystemEventHandler):
    """Logs every file system event with its type and path."""

    def on_created(self, event: FileSystemEvent) -> None:
        if not event.is_directory:
            log.info("file_created", extra={"path": event.src_path})
            print(f"[CREATED]  {event.src_path}")

    def on_modified(self, event: FileSystemEvent) -> None:
        if not event.is_directory:
            log.info("file_modified", extra={"path": event.src_path})
            print(f"[MODIFIED] {event.src_path}")

    def on_deleted(self, event: FileSystemEvent) -> None:
        if not event.is_directory:
            log.info("file_deleted", extra={"path": event.src_path})
            print(f"[DELETED]  {event.src_path}")

    def on_moved(self, event: FileMovedEvent) -> None:
        if not event.is_directory:
            log.info("file_moved", extra={
                "src":  event.src_path,
                "dest": event.dest_path,
            })
            print(f"[MOVED]    {event.src_path}{event.dest_path}")


# ─────────────────────────────────────────────────────────────────────────────
# 2. Pattern-filtered handler — only Python/config files
# ─────────────────────────────────────────────────────────────────────────────

class SourceChangeHandler(PatternMatchingEventHandler):
    """
    Only triggers on .py, .toml, .json, .yaml files.
    Ignores __pycache__, .git internals, and compiled artefacts.
    """

    def __init__(self, on_change: Callable[[str], None]) -> None:
        super().__init__(
            patterns=["*.py", "*.toml", "*.json", "*.yaml", "*.yml", "*.env"],
            ignore_patterns=["*/__pycache__/*", "*/.git/*", "*.pyc", "*.pyo"],
            ignore_directories=True,
            case_sensitive=False,
        )
        self._on_change = on_change

    def on_modified(self, event: FileSystemEvent) -> None:
        self._on_change(event.src_path)

    def on_created(self, event: FileSystemEvent) -> None:
        self._on_change(event.src_path)


# ─────────────────────────────────────────────────────────────────────────────
# 3. Debounced handler — collapse rapid on_modified bursts
# ─────────────────────────────────────────────────────────────────────────────

class DebouncedHandler(FileSystemEventHandler):
    """
    Many editors write files in multiple steps (save → temp → rename).
    Without debouncing, a single save fires 3–5 on_modified events.
    This handler waits `delay` seconds after the last event before firing.
    """

    def __init__(
        self,
        callback: Callable[[str], None],
        delay: float = 0.5,
        patterns: list[str] | None = None,
    ) -> None:
        super().__init__()
        self._callback = callback
        self._delay    = delay
        self._patterns = set(patterns or [])
        self._timers:  dict[str, threading.Timer] = {}
        self._lock = threading.Lock()

    def _matches(self, path: str) -> bool:
        if not self._patterns:
            return True
        p = Path(path)
        return any(p.match(pat) for pat in self._patterns)

    def _schedule(self, path: str) -> None:
        if not self._matches(path):
            return
        with self._lock:
            if path in self._timers:
                self._timers[path].cancel()
            timer = threading.Timer(self._delay, self._fire, args=(path,))
            self._timers[path] = timer
            timer.start()

    def _fire(self, path: str) -> None:
        with self._lock:
            self._timers.pop(path, None)
        log.debug("debounced_event", extra={"path": path})
        self._callback(path)

    def on_modified(self, event: FileSystemEvent) -> None:
        if not event.is_directory:
            self._schedule(event.src_path)

    def on_created(self, event: FileSystemEvent) -> None:
        if not event.is_directory:
            self._schedule(event.src_path)


# ─────────────────────────────────────────────────────────────────────────────
# 4. Queue-based handler — decouple event detection from processing
# ─────────────────────────────────────────────────────────────────────────────

class QueueHandler(FileSystemEventHandler):
    """
    Push events into a queue so the main thread (or worker pool) can
    process them without blocking the Observer thread.
    """

    def __init__(self) -> None:
        super().__init__()
        self.queue: Queue[FileSystemEvent] = Queue()

    def on_any_event(self, event: FileSystemEvent) -> None:
        if not event.is_directory:
            self.queue.put(event)


def queue_consumer(
    queue: Queue[FileSystemEvent],
    stop_event: threading.Event,
    processor: Callable[[FileSystemEvent], None],
) -> None:
    """Drain queue in a separate thread, calling processor for each event."""
    while not stop_event.is_set():
        try:
            event = queue.get(timeout=0.1)
            try:
                processor(event)
            except Exception as exc:
                log.exception("event_processing_failed", extra={"path": event.src_path})
            finally:
                queue.task_done()
        except Empty:
            continue


# ─────────────────────────────────────────────────────────────────────────────
# 5. File ingestion pipeline — watch drop folder, process new files
# ─────────────────────────────────────────────────────────────────────────────

class IngestionHandler(PatternMatchingEventHandler):
    """
    Watch a drop folder for new CSV/JSON files, process them as they arrive.
    ignore_directories=True — only triggers on file events.
    """

    def __init__(
        self,
        output_dir: Path,
        processed: set[str] | None = None,
    ) -> None:
        super().__init__(
            patterns=["*.csv", "*.json", "*.jsonl"],
            ignore_patterns=["*.tmp", "*.part"],
            ignore_directories=True,
            case_sensitive=False,
        )
        self._output_dir = output_dir
        self._processed  = processed or set()

    def on_created(self, event: FileCreatedEvent) -> None:
        path = Path(event.src_path)
        if str(path) in self._processed:
            return
        self._processed.add(str(path))
        self._ingest(path)

    def _ingest(self, path: Path) -> None:
        log.info("ingesting_file", extra={"path": str(path)})
        print(f"[INGEST] {path.name} ({path.stat().st_size} bytes)")
        # In production: parse CSV/JSON, validate, write to DB
        output = self._output_dir / f"done_{path.name}"
        output.touch()


# ─────────────────────────────────────────────────────────────────────────────
# 6. Observer factory — local vs network paths
# ─────────────────────────────────────────────────────────────────────────────

def make_observer(polling: bool = False) -> Observer:
    """
    Use PollingObserver for network mounts (NFS, SMB, Docker volumes)
    where inotify/kqueue events are not delivered to the client.
    """
    if polling:
        return PollingObserver(timeout=1)
    return Observer()


# ─────────────────────────────────────────────────────────────────────────────
# 7. Context manager — clean observer lifecycle
# ─────────────────────────────────────────────────────────────────────────────

class WatcherContext:
    """
    Context manager that starts an Observer on entry and stops it on exit.
    Usage:
        with WatcherContext("src/", handler) as _:
            while True:
                time.sleep(1)
    """

    def __init__(
        self,
        path: str | Path,
        handler: FileSystemEventHandler,
        recursive: bool = True,
        polling: bool = False,
    ) -> None:
        self._path      = str(path)
        self._handler   = handler
        self._recursive = recursive
        self._observer  = make_observer(polling)

    def __enter__(self) -> "WatcherContext":
        self._observer.schedule(self._handler, self._path, recursive=self._recursive)
        self._observer.start()
        log.info("watcher_started", extra={"path": self._path})
        return self

    def __exit__(self, *_) -> None:
        self._observer.stop()
        self._observer.join()
        log.info("watcher_stopped", extra={"path": self._path})


# ─────────────────────────────────────────────────────────────────────────────
# Demo
# ─────────────────────────────────────────────────────────────────────────────

if __name__ == "__main__":
    import tempfile

    with tempfile.TemporaryDirectory() as tmp:
        root = Path(tmp)
        (root / "src").mkdir()
        (root / "drop").mkdir()
        (root / "done").mkdir()

        changed: list[str] = []

        debounced = DebouncedHandler(
            callback=lambda p: changed.append(p),
            delay=0.1,
            patterns=["*.py"],
        )

        with WatcherContext(root / "src", debounced, recursive=True):
            # Simulate rapid saves (editor burst)
            for _ in range(5):
                (root / "src" / "app.py").write_text(f"# {time.time()}")
                time.sleep(0.02)

            time.sleep(0.3)  # wait for debounce timer

        print(f"Debounce fired {len(changed)} time(s) for 5 rapid writes: {changed}")

        # Ingestion
        ingester = IngestionHandler(output_dir=root / "done")
        with WatcherContext(root / "drop", ingester, recursive=False):
            for i in range(3):
                (root / "drop" / f"data_{i}.csv").write_text("a,b\n1,2\n")
                time.sleep(0.05)
            time.sleep(0.2)  # let events land

        print("Ingestion demo complete.")

For the inotifywait shell alternative — polling with inotifywait -m or fswatch requires spawning a subprocess, parsing unstructured text output, and re-implementing filtering logic in shell, while watchdog’s PatternMatchingEventHandler(patterns=["*.py"]) filters in Python, receives typed event objects (FileCreatedEvent, FileMovedEvent) with src_path and dest_path attributes, and runs cross-platform on Linux (inotify), macOS (kqueue), and Windows (ReadDirectoryChangesW) from a single code path. For the polling with os.listdir alternative — a polling loop that calls os.listdir() and compares snapshot diffs consumes CPU continuously and introduces latency proportional to the poll interval, while watchdog’s Observer uses the OS’s native async notification API so the thread wakes only when an event actually occurs — at idle, a watchdog Observer consumes near-zero CPU. The Claude Skills 360 bundle includes watchdog skill sets covering FileSystemEventHandler subclassing, PatternMatchingEventHandler with patterns/ignore_patterns, RegexMatchingEventHandler, Observer schedule and unschedule, debounced handler with threading.Timer to collapse editor burst saves, Queue-based handler for decoupled processing, file ingestion pipeline for drop-folder automation, PollingObserver for network mounts, WatcherContext manager for clean lifecycle, and multi-directory watch management. Start with the free tier to try file system monitoring code generation.

Keep Reading

AI

Claude Code for email.contentmanager: Python Email Content Accessors

Read and write EmailMessage body content with Python's email.contentmanager module and Claude Code — email contentmanager ContentManager for the class that maps content types to get and set handler functions allowing EmailMessage to support get_content and set_content with type-specific behaviour, email contentmanager raw_data_manager for the ContentManager instance that handles raw bytes and str payloads without any conversion, email contentmanager content_manager for the standard ContentManager instance used by email.policy.default that intelligently handles text plain text html multipart and binary content types, email contentmanager get_content_text for the handler that returns the decoded text payload of a text-star message part as a str, email contentmanager get_content_binary for the handler that returns the raw decoded bytes payload of a non-text message part, email contentmanager get_data_manager for the get-handler lookup used by EmailMessage get_content to find the right reader function for the content type, email contentmanager set_content text for the handler that creates and sets a text part correctly choosing charset and transfer encoding, email contentmanager set_content bytes for the handler that creates and sets a binary part with base64 encoding and optional filename Content-Disposition, email contentmanager EmailMessage get_content for the method that reads the message body using the registered content manager handlers, email contentmanager EmailMessage set_content for the method that sets the message body and MIME headers in one call, email contentmanager EmailMessage make_alternative make_mixed make_related for the methods that convert a simple message into a multipart container, email contentmanager EmailMessage add_attachment for the method that attaches a file or bytes to a multipart message, and email contentmanager integration with email.message and email.policy and email.mime and io for building high-level email readers attachment extractors text body accessors HTML readers and policy-aware MIME construction pipelines.

5 min read Feb 12, 2029
AI

Claude Code for email.charset: Python Email Charset Encoding

Control header and body encoding for international email with Python's email.charset module and Claude Code — email charset Charset for the class that wraps a character set name with the encoding rules for header encoding and body encoding describing how to encode text for that charset in email messages, email charset Charset header_encoding for the attribute specifying whether headers using this charset should use QP quoted-printable encoding BASE64 encoding or no encoding, email charset Charset body_encoding for the attribute specifying the Content-Transfer-Encoding to use for message bodies in this charset such as QP or BASE64, email charset Charset output_codec for the attribute giving the Python codec name used to encode the string to bytes for the wire format, email charset Charset input_codec for the attribute giving the Python codec name used to decode incoming bytes to str, email charset Charset get_output_charset for returning the output charset name, email charset Charset header_encode for encoding a header string using the charset's header_encoding method, email charset Charset body_encode for encoding body content using the charset's body_encoding, email charset Charset convert for converting a string from the input_codec to the output_codec, email charset add_charset for registering a new charset with custom encoding rules in the global charset registry, email charset add_alias for adding an alias name that maps to an existing registered charset, email charset add_codec for registering a codec name mapping for use by the charset machinery, and email charset integration with email.message and email.mime and email.policy and email.encoders for building international email senders non-ASCII header encoders Content-Transfer-Encoding selectors charset-aware message constructors and MIME encoding pipelines.

5 min read Feb 11, 2029
AI

Claude Code for email.utils: Python Email Address and Header Utilities

Parse and format RFC 2822 email addresses and dates with Python's email.utils module and Claude Code — email utils parseaddr for splitting a display-name plus angle-bracket address string into a realname and email address tuple, email utils formataddr for combining a realname and address string into a properly quoted RFC 2822 address with angle brackets, email utils getaddresses for parsing a list of raw address header strings each potentially containing multiple comma-separated addresses into a list of realname address tuples, email utils parsedate for parsing an RFC 2822 date string into a nine-tuple compatible with time.mktime, email utils parsedate_tz for parsing an RFC 2822 date string into a ten-tuple that includes the UTC offset timezone in seconds, email utils parsedate_to_datetime for parsing an RFC 2822 date string into an aware datetime object with timezone, email utils formatdate for formatting a POSIX timestamp or the current time as an RFC 2822 date string with optional usegmt and localtime flags, email utils format_datetime for formatting a datetime object as an RFC 2822 date string, email utils make_msgid for generating a globally unique Message-ID string with optional idstring and domain components, email utils decode_rfc2231 for decoding an RFC 2231 encoded parameter value into a tuple of charset language and value, email utils encode_rfc2231 for encoding a string as an RFC 2231 encoded parameter value, email utils collapse_rfc2231_value for collapsing a decoded RFC 2231 tuple to a Unicode string, and email utils integration with email.message and email.headerregistry and datetime and time for building address parsers date formatters message-id generators header extractors and RFC-compliant email construction utilities.

5 min read Feb 10, 2029

Put these ideas into practice

Claude Skills 360 gives you production-ready skills for everything in this article — and 2,350+ more. Start free or go all-in.

Back to Blog

Get 360 skills free