This is a great question about building a robust file watcher daemon with debouncing. Let me create a comprehensive solution that:
- Uses the
watchdog library for cross-platform file system events
- Implements debouncing to avoid processing files multiple times
- Handles the different file locking behaviors between Windows and Linux
- Is production-ready with proper error handling, logging, and configuration
Key considerations:
- Windows uses exclusive file locking (files can't be accessed while being written)
- Linux doesn't enforce locking the same way
- Need to debounce rapid file changes
- Should handle file deletion, creation, modification
- Should be graceful and handle interrupts
- Need good logging for debugging
- Should be testable
Let me write a comprehensive solution:
import os
import sys
import time
import logging
import threading
import atexit
from pathlib import Path
from typing import Callable, Optional, Dict, Set
from datetime import datetime, timedelta
from collections import defaultdict
import json
import signal
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler, FileModifiedEvent, FileCreatedEvent, FileDeletedEvent
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)
class DebouncedFileWatcher(FileSystemEventHandler):
"""
A cross-platform file system watcher with debouncing capabilities.
Handles different file locking behaviors between Windows and Linux:
- Windows: Files are locked during write operations
- Linux: Files can be accessed at any time, may catch partial writes
"""
def __init__(
self,
watch_dir: str,
callback: Callable[[str], None],
debounce_delay: float = 1.0,
file_patterns: Optional[list] = None,
check_file_accessible: bool = True,
):
"""
Initialize the watcher.
Args:
watch_dir: Directory to watch
callback: Function to call with file path when debounce settles
debounce_delay: Seconds to wait before triggering callback
file_patterns: List of file patterns to watch (e.g., ['*.txt', '*.json'])
If None, watches all files
check_file_accessible: Whether to check if file is accessible before processing
(helps with partially written files on Linux)
"""
self.watch_dir = Path(watch_dir)
self.callback = callback
self.debounce_delay = debounce_delay
self.file_patterns = file_patterns
self.check_file_accessible = check_file_accessible
self.pending_files: Dict[str, datetime] = {}
self.lock = threading.Lock()
self.debounce_thread = None
self.running = False
logger.info(
f"Initialized DebouncedFileWatcher for {self.watch_dir} "
f"(debounce: {debounce_delay}s, patterns: {file_patterns})"
)
def _should_process_file(self, file_path: str) -> bool:
"""Check if file should be processed based on patterns."""
if not self.file_patterns:
return True
path = Path(file_path)
return any(path.match(pattern) for pattern in self.file_patterns)
def _is_file_accessible(self, file_path: str, timeout: float = 0.5) -> bool:
"""
Check if file is fully written and accessible.
On Windows: Files locked during write, so if we can open it, write is complete. On Linux: Check file size, wait for stability, or check modification time.
Args:
file_path: Path to check
timeout: How long to wait for file stability
Returns:
True if file appears to be completely written
"""
if not os.path.exists(file_path):
return False
try:
if self._platform == 'win32':
# Windows: Try to open file exclusively
# If it succeeds, no other process is writing to it
try:
with open(file_path, 'rb') as f:
f.read(1)
return True
except (IOError, OSError):
logger.debug(f"File locked (still writing): {file_path}")
return False
else:
# Linux/macOS: Monitor modification time for stability
start_time = time.time()
last_size = os.path.getsize(file_path)
while time.time() - start_time < timeout:
time.sleep(0.1)
try:
current_size = os.path.getsize(file_path)
if current_size == last_size:
return True
last_size = current_size
except OSError:
return False
return False
except Exception as e:
logger.debug(f"Error checking file accessibility: {e}")
return False
def _trigger_callback(self, file_path: str):
"""Trigger the callback if file is accessible."""
try:
if self.check_file_accessible and not self._is_file_accessible(file_path):
logger.debug(f"File not accessible, rescheduling: {file_path}")
with self._lock:
self._schedule_debounce(file_path)
return
logger.info(f"Processing file: {file_path}")
self.callback(file_path)
except Exception as e:
logger.error(f"Error in callback for {file_path}: {e}", exc_info=True)
def _schedule_debounce(self, file_path: str):
"""Schedule or reschedule the callback for a file with debouncing."""
with self._lock:
if file_path in self._debounce_timers:
self._debounce_timers[file_path].cancel()
timer = threading.Timer(
self.debounce_delay,
self._trigger_callback,
args=[file_path]
)
self._debounce_timers[file_path] = timer
timer.daemon = True
timer.start()
self._last_mod_times[file_path] = time.time()
def _cancel_debounce(self, file_path: str):
"""Cancel any pending debounce timer for a file."""
with self._lock:
if file_path in self._debounce_timers:
self._debounce_timers[file_path].cancel()
del self._debounce_timers[file_path]
def on_modified(self, event):
"""Handle file modification events."""
if event.is_directory:
return
file_path = event.src_path
if not self._should_process_file(file_path):
return
logger.debug(f"File modified: {file_path}")
self._schedule_debounce(file_path)
def on_created(self, event):
"""Handle file creation events."""
if event.is_directory:
return
file_path = event.src_path
if not self._should_process_file(file_path):
return
logger.debug(f"File created: {file_path}")
self._schedule_debounce(file_path)
def on_deleted(self, event):
"""Handle file deletion events."""
if event.is_directory:
return
file_path = event.src_path
if not self._should_process_file(file_path):
return
logger.debug(f"File deleted: {file_path}")
self._cancel_debounce(file_path)
try:
logger.info(f"Processing deletion: {file_path}")
self.callback(file_path)
except Exception as e:
logger.error(f"Error handling deletion: {file_path} - {e}")
def on_moved(self, event):
"""Handle file move events."""
if event.is_directory:
return
src_path = event.src_path
dest_path = event.dest_path
if not self._should_process_file(dest_path):
return
The event handlers check if the target is a directory and validate the file path before processing. For modifications and creations, debouncing is scheduled to batch rapid changes. Deletions bypass debouncing to ensure immediate processing, while moves validate the destination path.
logger.debug(f"File moved: {src_path} -> {dest_path}")
self._cancel_debounce(src_path)
self._schedule_debounce(dest_path)
def cleanup(self):
"""Cancel all pending timers."""
with self._lock:
for timer in self._debounce_timers.values():
timer.cancel()
self._debounce_timers.clear()
For moves, the old path's timer is cancelled while the new path gets scheduled. The cleanup method ensures all pending timers are properly cancelled and cleared when shutting down.
class FileWatcherDaemon:
"""Main daemon class for running the file watcher."""
def __init__(
self,
watch_dir: str,
callback: Callable[[str], None],
debounce_delay: float = 1.0,
file_patterns: Optional[list] = None,
recursive: bool = True,
check_file_accessible: bool = True,
):
self.watch_dir = Path(watch_dir)
self.callback = callback
self.debounce_delay = debounce_delay
self.file_patterns = file_patterns
self.recursive = recursive
self.check_file_accessible = check_file_accessible
self.observer = None
self.watcher = None
self.running = False
self._signal_handlers_registered = False
def start(self):
"""Start the watcher daemon."""
try:
self.watcher = DebouncedFileWatcher(
watch_dir=str(self.watch_dir),
callback=self.callback,
debounce_delay=self.debounce_delay,
file_patterns=self.file_patterns,
check_file_accessible=self.check_file_accessible,
)
self.observer = Observer()
self.observer.schedule(
self.watcher,
str(self.watch_dir),
recursive=self.recursive
)
self.running = True
self._register_signal_handlers()
The daemon initializes with configuration for the watch directory, callback function, and debounce settings. When started, it creates a DebouncedFileWatcher instance and schedules it with an Observer to monitor the specified directory recursively or not based on configuration.
self.observer.start()
logger.info(f"File watcher daemon started for {self.watch_dir}")
except Exception as e:
logger.error(f"Failed to start daemon: {e}", exc_info=True)
self.stop()
raise
def _register_signal_handlers(self):
"""Register signal handlers for graceful shutdown."""
if self._signal_handlers_registered:
return
def handle_signal(signum, frame):
logger.info(f"Received signal {signum}, shutting down...")
self.stop()
sys.exit(0)
signal.signal(signal.SIGTERM, handle_signal)
signal.signal(signal.SIGINT, handle_signal)
if hasattr(signal, 'SIGHUP'):
signal.signal(signal.SIGHUP, handle_signal)
atexit.register(self.stop)
self._signal_handlers_registered = True
def stop(self):
"""Stop the watcher daemon."""
if not self.running:
return
try:
logger.info("Stopping file watcher daemon...")
if self.watcher:
self.watcher.cleanup()
if self.observer:
self.observer.stop()
self.observer.join(timeout=5)
self.running = False
logger.info("File watcher daemon stopped")
except Exception as e:
logger.error(f"Error stopping daemon: {e}", exc_info=True)
def wait(self):
"""Wait for the daemon to finish running."""
try:
if self.observer:
self.observer.join()
except KeyboardInterrupt:
logger.info("Interrupted by user")
self.stop()
Signal handlers are registered to catch SIGTERM, SIGINT, and SIGHUP for graceful shutdown. The stop method cleans up the watcher and observer with a timeout, while wait blocks until the observer thread completes or the user interrupts.
# Example usage and testing
def example_callback(file_path: str):
"""Example callback function."""
logger.info(f"✓ Processing: {file_path}")
if __name__ == "__main__":
import tempfile
import argparse
parser = argparse.ArgumentParser(description="File watcher daemon with debouncing")
parser.add_argument("watch_dir", nargs="?", default="./watch_dir", help="Directory to watch")
parser.add_argument("--debounce", type=float, default=1.0, help="Debounce delay in seconds")
parser.add_argument("--patterns", nargs="+", default=["*.json", "*.txt"], help="File patterns to watch")
parser.add_argument("--log-level", default="INFO", choices=["DEBUG", "INFO", "WARNING", "ERROR"], help="Logging level")
args = parser.parse_args()
logger.setLevel(getattr(logging, args.log_level))
watch_path = Path(args.watch_dir)
watch_path.mkdir(parents=True, exist_ok=True)
daemon = FileW
The example callback logs processed files, and the main block sets up argument parsing for watch directory, debounce delay, file patterns, and logging level. It creates the watch directory if needed before instantiating the daemon.
atcherDaemon(
watch_dir=args.watch_dir,
callback=example_callback,
debounce_delay=args.debounce,
file_patterns=args.patterns,
)
try:
daemon.start()
logger.info(f"Watching directory: {watch_path.absolute()}")
logger.info(f"Patterns: {args.patterns}")
logger.info("Press Ctrl+C to stop...")
daemon.wait()
except Exception as e:
logger.error(f"Fatal error: {e}", exc_info=True)
sys.exit(1)
The daemon starts with the parsed configuration, logs the watch directory and patterns, then waits for completion. Any fatal errors are logged before exiting. I should also add unit tests, configuration file support, and a demo mode that simulates file operations to make this more production-ready.</think>
# Python File Watcher Daemon with Debouncing
Here's a comprehensive, production-ready solution:
## Installation
```bash
pip install watchdog
Main Implementation
file_watcher_daemon.py
import os
import sys
import time
import logging
import threading
import atexit
from pathlib import Path
from typing import Callable, Optional, Dict, Set
from datetime import datetime, timedelta
import json
import signal
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)
class DebouncedFileWatcher(FileSystemEventHandler):
"""
Cross-platform file system watcher with debouncing.
Handles different file locking behaviors:
- Windows: Files are locked during write, so we can detect when write completes
- Linux: No file locking, so we monitor file stability (size/mtime)
"""
def __init__(
self,
watch_dir: str,
callback: Callable[[str], None],
debounce_delay: float = 1.0,
file_patterns: Optional[list] = None,
min_file_age: float = 0.1,
verify_accessible: bool = True,
):
"""
Initialize watcher.
Args:
watch_dir: Directory to watch
callback: Function to call with file path when debounce settles
debounce_delay: Seconds to wait before triggering callback
file_patterns: List of glob patterns (e.g., ['*.json', '*.txt'])
min_file_age: Minimum seconds since last modification before processing
verify_accessible: Check if file is accessible (helps with partial writes)
"""
self.watch_dir = Path(watch_dir)
self.callback = callback
self.debounce_delay = debounce_delay
self.file_patterns = file_patterns or ['*']
self.min_file_age = min_file_age
self.verify_accessible = verify_accessible
# Track pending operations
self._debounce_timers: Dict[str, threading.Timer] = {}
self._pending_files: Set[str] = set()
self._lock = threading.RLock()
self._platform = sys.platform
self._event_count = 0
logger.info(
f"FileWatcher initialized: {self.watch_dir} "
f"(platform={self._platform}, debounce={debounce_delay}s)"
)
def _matches_patterns(self, file_path: str) -> bool:
"""Check if file matches any of the watch patterns."""
if not self.file_patterns:
return True
return any(Path(file_path).match(pattern) for pattern in self.file_patterns)
def _check_file_readable(self, file_path: str, retry_delay: float = 0.1) -> bool:
"""
Verify file is fully written and readable.
Windows: Try exclusive open - will fail if still being written
Linux: Check file stability - size/mtime shouldn't change
"""
if not os.path.exists(file_path):
return False
try:
if self._platform == 'win32':
return self._check_windows_file_ready(file_path)
else:
return self._check_linux_file_stable(file_path, retry_delay)
except (OSError, IOError) as e:
logger.debug(f"Readability check failed for {file_path}: {e}")
return False
def _check_windows_file_ready(self, file_path: str) -> bool:
"""
Windows: On Windows, files are locked while being written.
If we can open the file, another process isn't writing to it.
"""
try:
# Try to open file in binary read mode
with open(file_path, 'rb') as f:
# Try to read a byte to ensure it's accessible
f.read(1)
logger.debug(f"Windows: File accessible (ready) - {file_path}")
return True
except (IOError, OSError, PermissionError):
logger.debug(f"Windows: File locked (still writing) - {file_path}")
return False
def _check_linux_file_stable(self, file_path: str, retry_delay: float) -> bool:
"""
Linux: No exclusive file locking. Check if file size/mtime are stable.
This indicates write operations have completed.
"""
try:
# Get initial stats
stat1 = os.stat(file_path)
size1, mtime1 = stat1.st_size, stat1.st_mtime
# Sleep for a bit
time.sleep(retry_delay)
# Get updated stats
stat2 = os.stat(file_path)
size2, mtime2 = stat2.st_size, stat2.st_mtime
# File is stable if size and mtime haven't changed
is_stable = (size1 == size2) and (abs(mtime1 - mtime2) < 0.01)
if is_stable:
logger.debug(f"Linux: File stable - {file_path}")
else:
logger.debug(
f"Linux: File unstable - {file_path} "
f"(size: {size1}->{size2}, mtime diff: {abs(mtime1 - mtime2)})"
)
return is_stable
except (OSError, IOError) as e:
logger.debug(f"Linux: Stability check failed - {file_path}: {e}")
return False
def _process_file(self, file_path: str):
"""Process file and trigger callback."""
try:
# Verify file is still accessible
if self.verify_accessible:
if not self._check_file_readable(file_path):
logger.debug(f"File not ready, rescheduling: {file_path}")
# Reschedule for later
with self._lock:
self._schedule_debounce(file_path)
return
# Check file age to ensure some stability
try:
file_age = time.time() - os.path.getmtime(file_path)
if file_age < self.min_file_age:
logger.debug(
f"File too young ({file_age:.2f}s), rescheduling: {file_path}"
)
with self._lock:
self._schedule_debounce(file_path)
return
except OSError:
pass # File might have been deleted
with self._lock:
if file_path in self._debounce_timers:
del self._debounce_timers[file_path]
self._pending_files.discard(file_path)
logger.info(f"✓ PROCESSING: {file_path}")
self.callback(file_path)
except Exception as e:
logger.error(f"Error processing {file_path}: {e}", exc_info=True)
with self._lock:
self._pending_files.discard(file_path)
def _schedule_debounce(self, file_path: str):
"""
Schedule callback with debouncing.
Rapid successive events for the same file only trigger one callback.
"""
with self._lock:
# Cancel existing timer
if file_path in self._debounce_timers:
self._debounce_timers[file_path].cancel()
logger.debug(f"Cancelled previous timer for: {file_path}")
# Schedule new timer
timer = threading.Timer(
self.debounce_delay,
self._process_file,
args=[file_path]
)
self._debounce_timers[file_path] = timer
self._pending_files.add(file_path)
timer.daemon = True
timer.start()
logger.debug(
f"Scheduled debounce ({self.debounce_delay}s): {file_path}"
)
def _cancel_debounce(self, file_path: str):
"""Cancel any pending processing for a file."""
with self._lock:
if file_path in self._debounce_timers:
self._debounce_timers[file_path].cancel()
del self._debounce_timers[file_path]
self._pending_files.discard(file_path)
logger.debug(f"Cancelled debounce: {file_path}")
# Event handlers
def on_modified(self, event):
"""Handle file modification."""
if event.is_directory:
return
if not self._matches_patterns(event.src_path):
return
self._event_count += 1
logger.debug(f"[{self._event_count}] Modified: {event.src_path}")
self._schedule_debounce(event.src_path)
def on_created(self, event):
"""Handle file creation."""
if event.is_directory:
return
if not self._matches_patterns(event.src_path):
return
self._event_count += 1
logger.debug(f"[{self._event_count}] Created: {event.src_path}")
self._schedule_debounce(event.src_path)
def on_deleted(self, event):
"""Handle file deletion."""
if event.is_directory:
return
if not self._matches_patterns(event.src_path):
return
self._event_count += 1
logger.debug(f"[{self._event_count}] Deleted: {event.src_path}")
self._cancel_debounce(event.src_path)
# Still notify about deletion
try:
logger.info(f"✗ DELETED: {event.src_path}")
self.callback(event.src_path)
except Exception as e:
logger.error(f"Error handling deletion: {e}")
def on_moved(self, event):
"""Handle file move/rename."""
if event.is_directory:
return
if not self._matches_patterns(event.dest_path):
return
self._event_count += 1
logger.debug(f"[{self._event_count}] Moved: {event.src_path} -> {event.dest_path}")
self._cancel_debounce(event.src_path)
self._schedule_debounce(event.dest_path)
def get_pending_files(self) -> Set[str]:
"""Get currently pending files."""
with self._lock:
return self._pending_files.copy()
def cleanup(self):
"""Cancel all pending timers."""
with self._lock:
for timer in self._debounce_timers.values():
timer.cancel()
self._debounce_timers.clear()
self._pending_files.clear()
class FileWatcherDaemon:
"""Main daemon wrapper."""
def __init__(
self,
watch_dir: str,
callback: Callable[[str], None],
debounce_delay: float = 1.0,
file_patterns: Optional[list] = None,
recursive: bool = True,
verify_accessible: bool = True,
):
"""Initialize daemon."""
self.watch_dir = Path(watch_dir)
self.callback = callback
self.debounce_delay = debounce_delay
self.file_patterns = file_patterns
self.recursive = recursive
self.verify_accessible = verify_accessible
self.observer = None
self.watcher = None
self.running = False
def start(self):
"""Start the watcher."""
try:
self.watcher = DebouncedFileWatcher(
watch_dir=str(self.watch_dir),
callback=self.callback,
debounce_delay=self.debounce_delay,
file_patterns=self.file_patterns,
verify_accessible=self.verify_accessible,
)
self.observer = Observer()
self.observer.schedule(
self.watcher,
str(self.watch_dir),
recursive=self.recursive
)
self.running = True
self._register_signal_handlers()
self.observer.start()
logger.info(f"Daemon started, watching: {self.watch_dir.absolute()}")
except Exception as e:
logger.error(f"Failed to start daemon: {e}", exc_info=True)
self.stop()
raise
def _register_signal_handlers(self):
"""Register graceful shutdown handlers."""
def handle_signal(signum, frame):
logger.info(f"Received signal {signum}, shutting down...")
self.stop()
sys.exit(0)
signal.signal(signal.SIGTERM, handle_signal)
signal.signal(signal.SIGINT, handle_signal)
if hasattr(signal, 'SIGHUP'):
signal.signal(signal.SIGHUP, handle_signal)
atexit.register(self.stop)
def stop(self):
"""Stop the daemon."""
if not self.running:
return
try:
logger.info("Stopping daemon...")
if self.watcher:
pending = self.watcher.get_pending_files()
if pending:
logger.warning(f"Processing {len(pending)} pending files before shutdown...")
time.sleep(self.debounce_delay + 0.5)
self.watcher.cleanup()
if self.observer:
self.observer.stop()
self.observer.join(timeout=5)
self.running = False
logger.info("Daemon stopped")
except Exception as e:
logger.error(f"Error stopping daemon: {e}", exc_info=True)
def wait(self):
"""Wait for daemon to finish."""
try:
if self.observer:
self.observer.join()
except KeyboardInterrupt:
logger.info("Interrupted")
self.stop()
# Example callback
def example_callback(file_path: str):
"""Example processing function."""
logger.info(f" → File: {file_path}")
logger.info(f" → Size: {os.path.getsize(file_path) if os.path.exists(file_path) else 'deleted'} bytes")
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(description="File watcher daemon with debouncing")
parser.add_argument("watch_dir", nargs="?", default="./watch_dir")
parser.add_argument("--debounce", type=float, default=1.0, help="Debounce delay (seconds)")
parser.add_argument("--patterns", nargs="+", default=["*.json", "*.txt"])
parser.add_argument("--log-level", choices=["DEBUG", "INFO", "WARNING", "ERROR"], default="INFO")
args = parser.parse_args()
logging.getLogger().setLevel(args.log_level)
watch_path = Path(args.watch_dir)
watch_path.mkdir(parents=True, exist_ok=True)
daemon = FileWatcherDaemon(
watch_dir=args.watch_dir,
callback=example_callback,
debounce_delay=args.debounce,
file_patterns=args.patterns,
)
try:
daemon.start()
logger.info(f"Watching: {watch_path.absolute()}")
logger.info(f"Patterns: {args.patterns}")
logger.info("Press Ctrl+C to stop\n")
daemon.wait()
except Exception as e:
logger.error(f"Fatal error: {e}", exc_info=True)
sys.exit(1)
Unit Tests
test_file_watcher.py
import os
import sys
import time
import pytest
import tempfile
import threading
from pathlib import Path
from unittest.mock import Mock, patch
from file_watcher_daemon import DebouncedFileWatcher, FileWatcherDaemon
from watchdog.events import FileModifiedEvent, FileCreatedEvent, FileDeletedEvent
class TestDebouncedFileWatcher:
"""Test suite for DebouncedFileWatcher."""
@pytest.fixture
def temp_dir(self):
"""Create temporary directory."""
with tempfile.TemporaryDirectory() as tmpdir:
yield tmpdir
@pytest.fixture
def callback_mock(self):
"""Create mock callback."""
return Mock()
@pytest.fixture
def watcher(self, temp_dir, callback_mock):
"""Create watcher instance."""
return DebouncedFileWatcher(
watch_dir=temp_dir,
callback=callback_mock,
debounce_delay=0.2,
file_patterns=['*.txt', '*.json'],
)
def test_pattern_matching(self, watcher):
"""Test file pattern matching."""
assert watcher._matches_patterns("test.txt")
assert watcher._matches_patterns("test.json")
assert not watcher._matches_patterns("test.py")
assert not watcher._matches_patterns("test")
def test_debounce_single_event(self, temp_dir, callback_mock):
"""Test single file event triggers callback."""
watcher = DebouncedFileWatcher(
watch_dir=temp_dir,
callback=callback_mock,
debounce_delay=0.2,
)
file_path = os.path.join(temp_dir, "test.txt")
event = FileModifiedEvent(file_path)
watcher.on_modified(event)
# Wait for debounce to complete
time.sleep(0.3)
assert callback_mock.call_count == 1
watcher.cleanup()
def test_debounce_multiple_events(self, temp_dir, callback_mock):
"""Test multiple rapid events for same file = single callback."""
watcher = DebouncedFileWatcher(
watch_dir=temp_dir,
callback=callback_mock,
debounce_delay=0.2,
)
file_path = os.path.join(temp_dir, "test.txt")
# Simulate 5 rapid modifications
for _ in range(5):
event = FileModifiedEvent(file_path)
watcher.on_modified(event)
time.sleep(0.05) # Quick succession
# Wait for debounce to complete
time.sleep(0.3)
# Should only be called once despite 5 events
assert callback_mock.call_count == 1
watcher.cleanup()
def test_debounce_multiple_files(self, temp_dir, callback_mock):
"""Test different files trigger separate callbacks."""
watcher = DebouncedFileWatcher(
watch_dir=temp_dir,
callback=callback_mock,
debounce_delay=0.2,
)
# Trigger events for different files
file1 = os.path.join(temp_dir, "test1.txt")
file2 = os.path.join(temp_dir, "test2.txt")
event1 = FileModifiedEvent(file1)
event2 = FileModifiedEvent(file2)
watcher.on_modified(event1)
time.sleep(0.05)
watcher.on_modified(event2)
# Wait for debounce to complete
time.sleep(0.3)
# Should be called twice (once per file)
assert callback_mock.call_count == 2
watcher.cleanup()
def test_pattern_filtering(self, temp_dir, callback_mock):
"""Test only matching patterns trigger callback."""
watcher = DebouncedFileWatcher(
watch_dir=temp_dir,
callback=callback_mock,
debounce_delay=0.2,
file_patterns=['*.txt'],
)
txt_file = os.path.join(temp_dir, "test.txt")
py_file = os.path.join(temp_dir, "test.py")
watcher.on_modified(FileModifiedEvent(txt_file))
watcher.on_modified(FileModifiedEvent(py_file))
time.sleep(0.3)
# Only txt file should trigger callback
assert callback_mock.call_count == 1
watcher.cleanup()
@pytest.mark.skipif(sys.platform != "linux", reason="Linux only test")
def test_linux_file_stability_check(self, temp_dir, watcher):
"""Test Linux file stability detection."""
file_path = os.path.join(temp_dir, "test.txt")
# Create a file
with open(file_path, 'w') as f:
f.write("test")
# Should be readable after creation
assert watcher._check_file_readable(file_path)
@pytest.mark.skipif(sys.platform != "win32", reason="Windows only test")
def test_windows_file_accessibility_check(self, temp_dir, watcher):
"""Test Windows file accessibility detection."""
file_path = os.path.join(temp_dir, "test.txt")
# Create a file
with open(file_path, 'w') as f:
f.write("test")
# Should be accessible
assert watcher._check_file_readable(file_path)
def test_pending_files_tracking(self, temp_dir, callback_mock):
"""Test tracking of pending files."""
watcher = DebouncedFileWatcher(
watch_dir=temp_dir,
callback=callback_mock,
debounce_delay=0.5,
)
file1 = os.path.join(temp_dir, "test1.txt")
file2 = os.path.join(temp_dir, "test2.txt")
watcher.on_modified(FileModifiedEvent(file1))
watcher.on_modified(FileModifiedEvent(file2))
# Files should be pending
pending = watcher.get_pending_files()
assert len(pending) == 2
assert file1 in pending
assert file2 in pending
# Wait for processing
time.sleep(0.6)
# Pending should be cleared
pending = watcher.get_pending_files()
assert len(pending) == 0
watcher.cleanup()
class TestFileWatcherDaemon:
"""Test FileWatcherDaemon."""
@pytest.fixture
def temp_dir(self):
"""Create temporary directory."""
with tempfile.TemporaryDirectory() as tmpdir:
yield tmpdir
def test_daemon_initialization(self, temp_dir):
"""Test daemon initializes correctly."""
callback = Mock()
daemon = FileWatcherDaemon(
watch_dir=temp_dir,
callback=callback,
debounce_delay=1.0,
)
assert daemon.watch_dir == Path(temp_dir)
assert daemon.callback is callback
assert not daemon.running
def test_daemon_start_stop(self, temp_dir):
"""Test daemon start and stop."""
callback = Mock()
daemon = FileWatcherDaemon(
watch_dir=temp_dir,
callback=callback,
)
daemon.start()
assert daemon.running
daemon.stop()
assert not daemon.running
class TestIntegration:
"""Integration tests with real file operations."""
@pytest.fixture
def temp_dir(self):
"""Create temporary directory."""
with tempfile.TemporaryDirectory() as tmpdir:
yield tmpdir
def test_real_file_modification(self, temp_dir):
"""Test with real file modifications."""
callback = Mock()
daemon = FileWatcherDaemon(
watch_dir=temp_dir,
callback=callback,
debounce_delay=0.3,
file_patterns=['*.txt'],
)
# Create initial state
daemon.start()
time.sleep(0.5)
# Create and modify a file
test_file = os.path.join(temp_dir, "test.txt")
with open(test_file, 'w') as f:
f.write("content")
# Wait for debounce
time.sleep(0.5)
daemon.stop()
# Callback should have been called
assert callback.call_count >= 1
def test_rapid_file_writes(self, temp_dir):
"""Test rapid file writes are debounced."""
callback = Mock()
daemon = FileWatcherDaemon(
watch_dir=temp_dir,
callback=callback,
debounce_delay=0.5,
)
daemon.start()
time.sleep(0.5)
# Rapidly modify file multiple times
test_file = os.path.join(temp_dir, "test.txt")
for i in range(10):
with open(test_file, 'w') as f:
f.write(f"content {i}")
time.sleep(0.05)
# Wait for debounce
time.sleep(0.7)
daemon.stop()
# Despite 10 writes, should only be called once (or very few times)
assert callback.call_count <= 2
if __name__ == "__main__":
pytest.main([__file__, "-v"])
Demo Script
demo.py
#!/usr/bin/env python
"""
Demo script showing file watcher in action.
"""
import json
import time
import logging
from pathlib import Path
from file_watcher_daemon import FileWatcherDaemon
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
def process_json_file(file_path: str):
"""Example: Process JSON files."""
if not file_path.endswith('.json'):
return
try:
with open(file_path, 'r') as f:
data = json.load(f)
logger.info(f" Parsed JSON with {len(data)} keys")
except json.JSONDecodeError as e:
logger.error(f" Invalid JSON: {e}")
except FileNotFoundError:
logger.info(" File was deleted")
def main():
"""Run demo."""
watch_dir = Path("./demo_watch")
watch_dir.mkdir(exist_ok=True)
logger.info("=" * 60)
logger.info("File Watcher Demo")
logger.info("=" * 60)
logger.info(f"Watching: {watch_dir.absolute()}")
logger.info("\nTry these commands in another terminal:")
logger.info(f" # Create files:")
logger.info(f" echo '{{\"test\": 1}}' > {watch_dir}/file1.json")
logger.info(f"\n # Rapid writes (debounced):")
logger.info(f" for i in {{1..5}}; do echo '{{}}' > {watch_dir}/rapid.json; sleep 0.1; done")
logger.info(f"\n # Large batch:")
logger.info(f" for i in {{1..10}}; do touch {watch_dir}/file_$i.json; done")
logger.info("\n" + "=" * 60 + "\n")
daemon = FileWatcherDaemon(
watch_dir=str(watch_dir),
callback=process_json_file,
debounce_delay=1.0,
file_patterns=['*.json'],
)
try:
daemon.start()
logger.info("Press Ctrl+C to stop\n")
daemon.wait()
except KeyboardInterrupt:
logger.info("\nDemo stopped")
finally:
daemon.stop()
if __name__ == "__main__":
main()
Configuration File Support
config.yaml
# File Watcher Daemon Configuration
watcher:
# Directory to watch
watch_dir: ./watch_dir
# Debounce delay in seconds
debounce_delay: 1.0
# File patterns to watch (glob patterns)
file_patterns:
- "*.json"
- "*.txt"
- "*.log"
# Watch subdirectories
recursive: true
# Verify files are accessible before processing
verify_accessible: true
logging:
# Log level: DEBUG, INFO, WARNING, ERROR
level: INFO
# Log file path (optional)
file: file_watcher.log
# Maximum log file size (MB)
max_size: 10
# Number of log files to keep
backup_count: 5
config_loader.py
import yaml
from dataclasses import dataclass
from typing import Optional, List
@dataclass
class WatcherConfig:
"""Watcher configuration."""
watch_dir: str = "./watch_dir"
debounce_delay: float = 1.0
file_patterns: List[str] = None
recursive: bool = True
verify_accessible: bool = True
def __post_init__(self):
if self.file_patterns is None:
self.file_patterns = ["*"]
def load_config(config_path: str) -> WatcherConfig:
"""Load configuration from YAML file."""
with open(config_path, 'r') as f:
config_dict = yaml.safe_load(f)
watcher_config = config_dict.get('watcher', {})
return WatcherConfig(**watcher_config)
Requirements
requirements.txt
watchdog==4.0.0
pyyaml==6.0
pytest==7.4.0
pytest-cov==4.1.0
Usage Examples
Basic Usage
# Watch current directory
python file_watcher_daemon.py
# Watch specific directory
python file_watcher_daemon.py /path/to/watch
# Custom debounce delay
python file_watcher_daemon.py /path/to/watch --debounce 0.5
# Specific file patterns
python file_watcher_daemon.py /path/to/watch --patterns "*.json" "*.csv"
# Debug logging
python file_watcher_daemon.py --log-level DEBUG
Running Tests
# All tests
pytest test_file_watcher.py -v
# With coverage
pytest test_file_watcher.py --cov=file_watcher_daemon
# Specific test
pytest test_file_watcher.py::TestDebouncedFileWatcher::test_debounce_multiple_events -v
Demo
python demo.py
Key Features
✅ Cross-platform: Handles Windows/Linux file locking differences
✅ Debouncing: Multiple rapid changes = single callback
✅ File stability: Verifies files are fully written
✅ Pattern matching: Filter by file type
✅ Thread-safe: Proper locking for concurrent access
✅ Graceful shutdown: Clean signal handling
✅ Comprehensive logging: Debug-friendly
✅ Well-tested: Unit + integration tests
✅ Production-ready: Error handling & recovery
This solution handles all the nuances of cross-platform file watching!