python
#!/usr/bin/env python3
"""
Python directory watcher daemon using watchdog.
Watches a directory for new files (non-directories), waits for the file to stop changing
(by monitoring size stability), then moves it to a processed directory with a timestamp prefix.
Usage:
python3 file_watcher.py --watch /path/to/watch --process /path/to/processed
python3 file_watcher.py --watch . --process ./processed # defaults
Handles SIGINT/SIGTERM gracefully. Runs indefinitely until signal received.
Non-recursive (only top-level directory).
Cross-platform (Linux/macOS/Windows).
"""
import os
import time
import sys
import signal
import argparse
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
class FileHandler(FileSystemEventHandler):
def __init__(self, watch_dir: str, process_dir: str):
self.watch_dir = os.path.abspath(watch_dir)
self.process_dir = os.path.abspath(process_dir)
def on_created(self, event):
if not event.is_directory:
filepath = event.src_path
self.process_file(filepath)
def process_file(self, filepath: str):
print(f"New file detected: {filepath}")
if not self.wait_for_stable(filepath):
print(f"File {filepath} unstable after timeout, skipping.")
return
try:
timestamp = time.strftime("%Y%m%d_%H%M%S")
basename = os.path.basename(filepath)
name, ext = os.path.splitext(basename)
newname = f"{timestamp}_{name}{ext}"
newpath = os.path.join(self.process_dir, newname)
os.rename(filepath, newpath)
print(f"Processed: {filepath} -> {newpath}")
except Exception as e:
print(f"Error processing {filepath}: {e}")
def wait_for_stable(self, filepath: str, timeout: int = 30, interval: float = 0.5) -> bool:
"""Wait until file size stabilizes, indicating it's fully written."""
last_size = -1
start_time = time.time()
while time.time() - start_time < timeout:
try:
current_size = os.path.getsize(filepath)
if current_size == last_size and last_size != -1:
return True
last_size = current_size
except OSError:
return False
time.sleep(interval)
return False
def signal_handler(sig, frame, observer):
"""Graceful shutdown on SIGINT/SIGTERM."""
print("\nShutting down watcher...")
observer.stop()
sys.exit(0)
def main():
parser = argparse.ArgumentParser(description="Directory watcher daemon for new files.")
parser.add_argument(
"--watch",
default=".",
help="Directory to watch for new files (default: current dir)",
)
parser.add_argument(
"--process",
default="./processed",
help="Directory to move processed files to (default: ./processed)",
)
args = parser.parse_args()
watch_dir = os.path.abspath(args.watch)
process_dir = os.path.abspath(args.process)
os.makedirs(process_dir, exist_ok=True)
print(f"Watching: {watch_dir}")
print(f"Processing to: {process_dir}")
print("Press Ctrl+C to stop.\n")
event_handler = FileHandler(watch_dir, process_dir)
observer = Observer()
observer.schedule(event_handler, watch_dir, recursive=False)
observer.start()
# Register signal handlers
signal.signal(signal.SIGINT, lambda sig, frame: signal_handler(sig, frame, observer))
signal.signal(signal.SIGTERM, lambda sig, frame: signal_handler(sig, frame, observer))
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
observer.stop()
finally:
observer.join()
print("Watcher stopped.")
if __name__ == "__main__":
main()