Recipe 10.3 · Python
FileSystemWatcher Done Right
The Python listings are conversions of the book's C# code to Python 3.12. Each file's header says what it needs to run. The explanations were written for the C# version, so some names in the text refer to .NET.
Problem
A service needs to process files as they arrive in a folder. FileSystemWatcher looks like the answer, and then the bugs start. It raises Created and several Changed events for one file. It raises Created before the writer has finished, so the file is locked or incomplete. It drops events when many files arrive at once. And files that arrive while the service is stopped are never seen at all.
The way it's often written
Anti-pattern: shown so you can recognize it. Don't copy this one.
ReadAllText fails with "file in use" for anything larger than a few kilobytes, and the exception is lost on a thread-pool thread. A bulk copy of 500 files overflows the watcher's buffer and some files are never processed.
Requirements: Python 3.12+. Install: pip install watchdog
"""Naive folder watcher that imports and deletes a file the moment it appears
Source: ImproveCode, Chapter 10, Recipe 10.3 "FileSystemWatcher Done Right"
Section: The way it's often written
Book page: 211 -- original C# listing
Converted from C# to Python.
ANTI-PATTERN: kept deliberately faithful to the C# 'not to copy' example; do not use.
FileSystemWatcher.Created -> watchdog FileSystemEventHandler.on_created; the file
may still be half-written or locked, and events can be lost on buffer overflow.
"""
import os
from collections.abc import Callable
from watchdog.events import FileSystemEvent, FileSystemEventHandler
from watchdog.observers import Observer
def start_watcher(folder: str, import_text: Callable[[str], None]) -> Observer:
class _Handler(FileSystemEventHandler):
def on_created(self, event: FileSystemEvent) -> None:
with open(event.src_path, encoding="utf-8") as f:
text = f.read()
import_text(text)
os.remove(event.src_path)
watcher = Observer()
watcher.schedule(_Handler(), folder)
watcher.start() # EnableRaisingEvents = true
return watcher
The improved recipe
Treat the watcher as a hint, not the source of truth. Its events only put a path on a queue. One consumer takes paths from the queue, waits until each file can be opened exclusively, and processes it. On startup and whenever the watcher reports an error, a full scan of the folder queues everything that is there, so nothing is missed.
NuGet package: Microsoft.Extensions.Hosting.Abstractions.
A usage snippet for a concrete service. It only implements the processing step, and it must move the file when done so a rescan does not process it again:
Requirements: Python 3.12+. Install: pip install watchdog
"""Folder watcher service: dedupe events into a queue, wait for unlocked files
Source: ImproveCode, Chapter 10, Recipe 10.3 "FileSystemWatcher Done Right"
Section: The improved recipe
Book page: 211-214 -- original C# listing
Converted from C# to Python.
BackgroundService -> asyncio task (run()); FileSystemWatcher -> watchdog Observer;
Channel<string> -> asyncio.Queue fed thread-safely via loop.call_soon_threadsafe;
ILogger -> logging. The "ready" probe opens the file exclusively where the OS
supports it (Windows share modes); on POSIX it only checks it can be opened.
"""
from __future__ import annotations
import asyncio
import fnmatch
import logging
import os
import threading
from abc import ABC, abstractmethod
from watchdog.events import FileSystemEvent, FileSystemEventHandler
from watchdog.observers import Observer
class FolderWatcherService(ABC):
def __init__(self, folder: str, filter: str, logger: logging.Logger) -> None:
self.folder = folder
self.filter = filter
self.logger = logger
self._queue: asyncio.Queue[str] = asyncio.Queue()
self._queued: set[str] = set()
self._queued_lock = threading.Lock()
self._loop: asyncio.AbstractEventLoop | None = None
@abstractmethod
async def process_file_async(self, path: str) -> None: ...
async def run(self) -> None:
"""Equivalent of ExecuteAsync; cancel the task to stop."""
self._loop = asyncio.get_running_loop()
os.makedirs(self.folder, exist_ok=True)
service = self
class _Handler(FileSystemEventHandler):
def on_created(self, event: FileSystemEvent) -> None:
if not event.is_directory:
service._enqueue(event.src_path)
def on_modified(self, event: FileSystemEvent) -> None:
if not event.is_directory:
service._enqueue(event.src_path)
def on_moved(self, event: FileSystemEvent) -> None:
if not event.is_directory:
service._enqueue(event.dest_path)
watcher = Observer()
watcher.schedule(_Handler(), self.folder, recursive=False)
watcher.start()
try:
self._enqueue_existing()
while True:
path = await self._queue.get()
with self._queued_lock:
self._queued.discard(self._key(path))
if not os.path.exists(path):
continue
try:
if await self._wait_until_ready_async(path):
await self.process_file_async(path)
else:
self.logger.warning("%s stayed locked", path)
self._enqueue(path)
except asyncio.CancelledError:
raise
except Exception:
self.logger.exception("Failed to process %s", path)
finally:
watcher.stop()
watcher.join()
def on_watcher_error(self, exc: BaseException) -> None:
"""Watchdog has no Error event; call this from an observer error hook."""
self.logger.warning("Watcher error on %s; rescanning", self.folder,
exc_info=exc)
self._enqueue_existing()
def _enqueue_existing(self) -> None:
for name in os.listdir(self.folder):
path = os.path.join(self.folder, name)
if os.path.isfile(path) and fnmatch.fnmatch(name, self.filter):
self._enqueue(path)
@staticmethod
def _key(path: str) -> str:
return path.casefold() # OrdinalIgnoreCase
def _enqueue(self, path: str) -> None:
name = os.path.basename(path)
if name.startswith(".") or name.lower().endswith(".tmp"):
return
if not fnmatch.fnmatch(name, self.filter):
return
with self._queued_lock:
key = self._key(path)
if key in self._queued:
return
self._queued.add(key)
assert self._loop is not None
# Watchdog callbacks run on a worker thread.
self._loop.call_soon_threadsafe(self._queue.put_nowait, path)
@staticmethod
async def _wait_until_ready_async(path: str) -> bool:
for _attempt in range(30):
try:
# Exclusive open where supported (FileShare.None on Windows).
fd = os.open(path, os.O_RDONLY | getattr(os, "O_EXLOCK", 0))
os.close(fd)
return True
except OSError:
if not os.path.exists(path):
raise
await asyncio.sleep(1)
return False
Requirements: Python 3.12+. Standard library only, nothing to install.
"""Invoice drop-folder service: import each CSV, then move it to processed/
Source: ImproveCode, Chapter 10, Recipe 10.3 "FileSystemWatcher Done Right"
Section: The improved recipe
Book page: 214 -- original C# listing
Converted from C# to Python.
Subclasses FolderWatcherService from p211; ILogger<T> -> logging.getLogger;
File.Move(overwrite: true) -> os.replace.
"""
from __future__ import annotations
import logging
import os
from p211_r10_3_folder_watcher_service_queue import FolderWatcherService
class InvoiceDropService(FolderWatcherService):
def __init__(self, log: logging.Logger | None = None) -> None:
super().__init__(r"D:\drop\invoices", "*.csv",
log or logging.getLogger(__name__))
async def process_file_async(self, path: str) -> None:
await self._import_invoices_async(path)
done = os.path.join(self.folder, "processed", os.path.basename(path))
os.makedirs(os.path.dirname(done), exist_ok=True)
os.replace(path, done)
@staticmethod
async def _import_invoices_async(path: str) -> None:
return None
How it works
The event handlers do almost nothing: they call Enqueue, which ignores temp files and adds the path to the channel only if it is not already queued. Five Changed events for one file become one queue entry. Because the handlers return immediately, the watcher's internal buffer drains quickly, which is the best defense against overflow. The buffer is also raised to 64 KB, the largest size Microsoft recommends.
The consumer is a single loop, so files are processed one at a time in arrival order, and exceptions are caught and logged per file instead of vanishing on a thread-pool thread. WaitUntilReadyAsync tries to open the file with FileShare.None. That fails while any other process has the file open, so a successful open means the writer is done. After 30 seconds of failures the path is put back on the queue for later.
EnqueueExisting runs at startup, to pick up files that arrived while the service was stopped, and on every Error event, which is how the watcher reports a buffer overflow. Since processed files are moved away, a rescan only finds work that is still pending. The watcher becomes a way to react quickly; the scan is what makes the service correct.
Variations and pitfalls
- Network folders. Watchers on UNC paths lose their connection when the file server restarts, and the
Errorevent is the only clue. Add a periodic scan, every few minutes, with aPeriodicTimer(Chapter 14). - Ask senders to rename. The most reliable drop protocol is for the sender to upload as
name.tmpand rename when finished. The watcher then sees aRenamedevent for a complete file. - Poison files. A file that always fails is logged on every rescan. Move failures to an
errorsubfolder after a few attempts.