Write a Python file watcher daemon using watchdog with debouncing - if a file is saved 5 times in one second, only trigger processing once after things settle. Handle the differences in file locking behavior between Windows and Linux.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Outlined a watchdog-based Python daemon using a debouncing Timer per file path to consolidate rapid changes, with retries on file open to handle Windows locking behavior; Linux reads proceed without delay. The approach cancels/reschedules timers on new events to process only once after files settle, supporting cross-platform operation with graceful shutdown.
Below is a self‑contained example of a debouncing file watcher built on top of watchdog. It will coalesce bursts of changes to the same path into a single callback once things have “settled”, and it retries opening files on Windows to work around transient sharing/locking errors.
Save it as e.g. watcher.py and run it with python watcher.py /path/to/watch:
python
#!/usr/bin/env python3
import logging
import os
import platform
import threading
import time
from typing import Callable
from watchdog.events import FileSystemEvent, FileSystemEventHandler
from watchdog.observers import Observer
from watchdog.observers.polling import PollingObserver
log = logging.getLogger(__name__)
def safe_process(path: str, fn: Callable[[str], None],
retries: int = 10, delay: float = 0.1) -> None:
"""
Call fn(path), retrying on common Windows locking errors.
On Linux/Unix this will typically run once; on Windows we may need
to wait for the writer to close the handle.
"""
for attempt in range(1, retries + 1):
try:
fn(path)
return
except (PermissionError, OSError) as e:
# Only retry on likely sharing violations/locks
if platform.system().lower().startswith("win"):
log.debug("Retry %d/%d opening %s: %s", attempt, retries, path, e)
time.sleep(delay)
else:
raise
log.error("Giving up on %s after %d retries", path, retries)
class DebouncedEventHandler(FileSystemEventHandler):
"""
Watchdog event handler that debounces bursts of events per path.
"""
def __init__(self, callback: Callable[[str], None],
debounce_seconds: float = 1.0):
super().__init__()
self._callback = callback
self._debounce_seconds = debounce_seconds
self._timers: dict[str, threading.Timer] = {}
self._lock = threading.Lock()
def on_any_event(self, event: FileSystemEvent) -> None:
# Ignore directory events; adjust if you want to debounce dirs too.
if event.is_directory:
return
path = event.src_path
# We treat created/modified/moved/deleted the same for debouncing purposes.
self._schedule(path)
def _schedule(self, path: str) -> None:
with self._lock:
# Cancel any pending timer for this path
t = self._timers.pop(path, None)
if t:
t.cancel()
t = threading.Timer(self._debounce_seconds, self._fire, args=(path,))
t.daemon = True
self._timers[path] = t
t.start()
def _fire(self, path: str) -> None:
with self._lock:
# Remove timer entry if it hasn't been replaced
self._timers.pop(path, None)
log.info("Debounced event for %s", path)
safe_process(path, self._callback)
def process_file(path: str) -> None:
"""
Replace this with whatever processing you want to do.
For demonstration, we just read the file and log its size.
"""
if not os.path.exists(path):
log.warning("File %s no longer exists", path)
return
with open(path, "rb") as fh:
data = fh.read()
log.info("Processed %s (%d bytes)", path, len(data))
def main():
import argparse
parser = argparse.ArgumentParser(description="Debounced watchdog daemon")
parser.add_argument("path", help="Directory to watch")
parser.add_argument("-d", "--debounce", type=float, default=1.0,
help="Debounce interval in seconds (default: 1.0)")
parser.add_argument("-p", "--polling", action="store_true",
help="Use polling observer instead of native")
parser.add_argument("-v", "--verbose", action="store_true",
help="Enable debug logging")
args = parser.parse_args()
logging.basicConfig(
level=logging.DEBUG if args.verbose else logging.INFO,
format="%(asctime)s %(levelname)s %(message)s",
)
watch_dir = os.path.abspath(args.path)
if not os.path.isdir(watch_dir):
raise SystemExit(f"{watch_dir} is not a directory")
# Choose observer; PollingObserver can be more robust on network drives.
if args.polling:
observer_cls = PollingObserver
else:
observer_cls = Observer
observer = observer_cls()
handler = DebouncedEventHandler(process_file, debounce_seconds=args.debounce)
observer.schedule(handler, watch_dir, recursive=True)
observer.daemon = True
observer.start()
log.info("Watching %s (debounce=%ss)", watch_dir, args.debounce)
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
log.info("Stopping")
finally:
observer.stop()
observer.join()
if __name__ == "__main__":
main()
How it works
DebouncedEventHandler subclasses FileSystemEventHandler and keeps a threading.Timer per path. Whenever an event comes in for that path, any existing timer is cancelled and a new one is started. Only when there have been no new events for debounce_seconds will _fire be called.
safe_process wraps your actual processing and retries on PermissionError/OSError that commonly occur on Windows when another process still has the file open. On Linux these errors are rare and will be raised immediately.
process_file is a placeholder; replace it with whatever you need to do when a file has “settled”.
The script can use Observer (native OS notifications) or PollingObserver (periodic scan) depending on your environment.
With a 1‑second debounce, five rapid saves of the same file will coalesce into a single process_file invocation after ~1 second of quiescence.