#!/usr/bin/env python3
"""
File Change Monitor Script
==========================
This script uses the `watchdog` library to monitor a specified directory (or file)
for changes (create, modify, delete, move events). When an event occurs, it triggers
a customizable action, such as printing details or running a shell command.
Requirements:
- Install watchdog: `pip install watchdog`
Usage:
python file_monitor.py /path/to/watch [--recursive] [--command "your shell command"]
Examples:
python file_monitor.py . # Watch current dir, print events
python file_monitor.py /home/user/docs --recursive # Recursive watch
python file_monitor.py README.md --command "echo 'File changed!' && git add README.md"
Arguments:
path : Path to file or directory to watch (default: current directory '.')
--recursive : Watch subdirectories recursively (default: False)
--command : Shell command to run on each event (default: print event details)
--ignore : Glob patterns to ignore (e.g., '*.tmp,*.log') (default: None)
"""
import argparse
import os
import subprocess
import sys
import time
from pathlib import Path
from watchdog.events import FileSystemEventHandler
from watchdog.observers import Observer
class FileChangeHandler(FileSystemEventHandler):
def __init__(self, command=None, ignore_patterns=None):
self.command = command
self.ignore_patterns = ignore_patterns or []
def _should_ignore(self, path):
path = Path(path).name
return any(path.endswith(pattern.lstrip('*')) for pattern in self.ignore_patterns)
def on_any_event(self, event):
# Skip if it's a directory event (optional; customize as needed)
if event.is_directory:
return
# Skip ignored patterns
if self._should_ignore(event.src_path):
return
event_type = event.event_type
src_path = event.src_path
if event.event_type == 'moved':
src_path = f"{event.src_path} -> {event.dest_path}"
print(f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] {event_type.upper()} on: {src_path}", flush=True)
# Trigger custom command if provided
if self.command:
try:
full_cmd = self.command.replace('{path}', src_path).replace('{event}', event_type)
subprocess.run(full_cmd, shell=True, check=False, capture_output=False)
except Exception as e:
print(f"Error running command: {e}", file=sys.stderr)
def main():
parser = argparse.ArgumentParser(description="Monitor file changes and trigger events.")
parser.add_argument('path', nargs='?', default='.', help='Path to watch (default: current dir)')
parser.add_argument('--recursive', '-r', action='store_true', help='Watch recursively')
parser.add_argument('--command', '-c', help='Shell command to run on events (supports {path}, {event})')
parser.add_argument('--ignore', '-i', nargs='*', default=[], help='Glob patterns to ignore (e.g., "*.tmp")')
args = parser.parse_args()
path = os.path.abspath(args.path)
if not os.path.exists(path):
print(f"Error: Path '{path}' does not exist.", file=sys.stderr)
sys.exit(1)
print(f"Watching '{path}' {'(recursive)' if args.recursive else ''}...")
print("Press Ctrl+C to stop.\n")
event_handler = FileChangeHandler(command=args.command, ignore_patterns=args.ignore)
observer = Observer()
observer.schedule(event_handler, path, recursive=args.recursive)
observer.start()
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
observer.stop()
print("\nMonitoring stopped.")
observer.join()
if __name__ == '__main__':
main()
How to Use
- Install dependency:
pip install watchdog
- Run basic monitoring (prints events):
python file_monitor.py /path/to/folder
- Recursive watch with custom command (e.g., auto-commit git changes):
python file_monitor.py . --recursive --command "echo 'Changed: {path}' && git add {path} && git commit -m 'Auto: {event} {path}'"
- Ignore files:
python file_monitor.py . --ignore "*.pyc" "__pycache__"
Features
- Cross-platform: Works on Linux, macOS, Windows.
- Efficient: Uses native OS APIs via
watchdog.
- Customizable triggers: Print details or run shell commands with placeholders
{path} and {event}.
- Filters: Ignore directories, specific patterns.
- Graceful exit: Ctrl+C to stop.
This script is production-ready for basic use cases. Extend the FileChangeHandler class for more complex events (e.g., webhooks, database updates).