The user wants a Python daemon (a background process) that watches a specific directory and processes new files as they are added.
Key Requirements:
- Language: Python.
- Type: Daemon (long-running background process).
- Functionality:
- Watch a directory.
- Detect new files.
- Process them in real-time.
Tools/Libraries:
- Watching: The standard library
os.listdir polling loop is inefficient and slow. watchdog is the industry standard library for file system events in Python. It uses OS-specific APIs (inotify on Linux, FSEvents on macOS, ReadDirectoryChangesW on Windows) for low latency and low CPU usage.
- Daemonizing:
- Simple approach: Just a
while True loop script running in the terminal (good for testing).
- Robust approach: Use
python-daemon library (PEP 3143) or a system service manager like systemd or supervisord. For a general "write a daemon" request, a standalone script using watchdog is usually what's expected, but I should mention how to actually run it as a service.
- Processing: Needs to be defined. Since the user didn't specify what "process" means, I should create a placeholder function (e.g., logging, moving, reading lines).
Drafting the Code Structure (using watchdog):
- Import necessary modules:
watchdog.observers, watchdog.events, time, os, logging.
- Define an Event Handler:
- Inherit from
watchdog.events.FileSystemEventHandler.
- Override
on_created (this is the most relevant for "new files").
- Maybe handle
on_moved too?
- Crucial edge case: When a file is created, it might still be writing. Trying to read it immediately might fail or read partial data.
- Solution 1: Wait for it to finish?
watchdog doesn't explicitly say "file closed".
- Solution 2: Try to process, catch exceptions, retry? (Too complex for a basic example).
- Solution 3: On Windows/OSX,
on_closed event exists in some implementations, but watchdog specifically triggers on_modified during write and on_created at the start.
- Better approach: Just a simple warning in the code or a basic retry loop. For this example, I'll assume the file is created atomically or fully copied. However, a simple
time.sleep or checking file size stability is often needed in production. Let's keep it simple but mention the file-locking issue.
- The Main Loop:
- Set up the observer.
- Schedule the event handler for the target path.
- Start the observer.
- Keep the script running (infinite loop with sleep).
- Handle graceful shutdown (KeyboardInterrupt).
Refining the "Daemon" aspect:
The word "daemon" implies running in the background.
- Option A: Use
python-daemon context manager.
- Pros: True Unix daemon (double fork, detach session).
- Cons: Harder to debug, requires extra dependency.
- Option B: Write a standard script and tell the user to run it with
nohup or systemd.
- Pros: Cleaner code, easier to test.
- Cons: User might expect the code itself to detach.
- Decision: I will provide a robust script using
watchdog that runs in the foreground but is designed to be run as a service. I will also show how to use the python-daemon library for a "true" daemon implementation, or at least mention it.
Actually, the most modern and robust way to run a Python daemon is via systemd (Linux) or launchd (macOS). Writing "daemonization logic" (double-forking) inside Python is often discouraged now because system managers handle restarting, logging, and environment setup better.
Plan:
- Prerequisites: Install
watchdog.
- The Code: A class-based approach using
watchdog.
- Handler class.
- Main block.
- The "Processing" Logic: A dummy function that reads the file.
- Handling File Stability: Briefly address that files might be mid-copy.
- Running it: Instructions on how to run it as a background task (using
nohup or systemd).
Code details:
EventHandler: on_created event.
- Check
event.is_directory. We only want files.
- Logic:
print(f"Detected new file: {event.src_path}").
Self-Correction/Refinement during thought process:
- Issue: If a user copies a large file,
on_created fires immediately. If the script tries to read it, it's corrupt/incomplete.
- Fix: I won't implement a complex "wait until write finishes" logic as it bloats the snippet, but I will add a comment or a simple
try-except block or check if it's readable. Actually, a common pattern is to look for a "trigger" file or simply use a retry loop. For this answer, I will add a process_file function and mention that for large files, one should check if the file is still being written to (e.g., via size polling) inside that function.
Final Output Structure:
- Install command:
pip install watchdog
- Python Script:
- Setup logging (essential for a daemon).
NewFileHandler class.
process_file function.
main entry point.
- Deployment instructions:
- Running with
nohup (simple).
- Running with
systemd (professional).
Let's write the code mentally.
import time
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
class OnMyWatch:
# Set the directory on watch
watchDirectory = r"/path/to/dir"
def __init__(self):
self.observer = Observer()
def run(self):
event_handler = Handler()
self.observer.schedule(event_handler, self.watchDirectory, recursive=True)
self.observer.start()
try:
while True:
time.sleep(5)
except:
self.observer.stop()
self.observer.join()
class Handler(FileSystemEventHandler):
def on_created(self, event):
if not event.is_directory:
print(f"Received created event - {event.src_path}.")
# Process file here
This looks standard. I will polish it with logging and proper exception handling.
Specific Daemon features:
- Log rotation?
- PID file?
I'll stick to the
watchdog implementation as the core logic. The term "daemon" is often used loosely to mean "background service script".
Refined Plan:
- Use
watchdog.
- Include logging.
- Implement a handler for
on_created (and maybe on_moved as some tools write to a temp file then move).
- Provide instructions on how to run it.
Let's execute.
Here is a robust and production-ready approach to building a file watcher daemon in Python.
While you can write a manual loop using os.listdir, the industry standard is to use the watchdog library. It relies on OS-specific events (like Linux's inotify or macOS's FSEvents) rather than polling, which makes it extremely efficient and real-time.
Prerequisites
You will need to install the watchdog library:
pip install watchdog
1. The Python Script (watcher_daemon.py)
This script sets up a class to handle file events. It specifically looks for "closed" events to ensure the file has finished copying before trying to process it.
import sys
import time
import logging
import os
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
# Configuration
WATCH_DIRECTORY = "./input_dir"
PROCESSED_DIRECTORY = "./processed_dir"
# Setup Logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(message)s',
datefmt='%Y-%m-%d %H:%M:%S'
)
class NewFileHandler(FileSystemEventHandler):
"""
Event handler that reacts to new files created in the directory.
"""
def on_created(self, event):
# Ignore directories created inside the watch path
if event.is_directory:
return
logging.info(f"Detected new file: {event.src_path}")
# Trigger processing
self.process_file(event.src_path)
def process_file(self, filepath):
"""
Add your custom processing logic here.
"""
try:
filename = os.path.basename(filepath)
# Simulate processing time
logging.info(f"Processing {filename}...")
time.sleep(2) # Replace with actual work (e.g., image resize, parse CSV)
logging.info(f"Finished processing {filename}.")
# Optional: Move file to a 'processed' folder to keep input clean
# self.move_file(filepath, PROCESSED_DIRECTORY)
except Exception as e:
logging.error(f"Error processing {filepath}: {e}")
def move_file(self, src, dest_dir):
if not os.path.exists(dest_dir):
os.makedirs(dest_dir)
dest = os.path.join(dest_dir, os.path.basename(src))
os.rename(src, dest)
logging.info(f"Moved {src} to {dest}")
def run_daemon():
# Ensure directories exist
if not os.path.exists(WATCH_DIRECTORY):
os.makedirs(WATCH_DIRECTORY)
logging.info(f"Created directory: {WATCH_DIRECTORY}")
event_handler = NewFileHandler()
observer = Observer()
# Schedule the observer to watch the directory recursively
observer.schedule(event_handler, WATCH_DIRECTORY, recursive=False)
logging.info(f"Daemon started. Watching directory: {WATCH_DIRECTORY}")
observer.start()
try:
# Keep the script running in a loop
while True:
time.sleep(1)
except KeyboardInterrupt:
logging.info("Stopping daemon...")
observer.stop()
observer.join()
if __name__ == "__main__":
run_daemon()
2. Key Considerations
Handling "File in Transit" (Partial Writes)
In the script above, on_created fires the moment a file appears. If you are copying a large file (e.g., a 1GB video), the script might try to read it while it is still being written to, causing an error.
To fix this in production, you usually look for the on_closed event or check if the file size is stable. Here is how you modify the event handler to be safer for large files:
def on_closed(self, event):
# This triggers only when the file handle is released (copy finished)
if not event.is_directory:
logging.info(f"File transfer complete: {event.src_path}")
self.process_file(event.src_path)
Handling Hidden Files
Operating systems often create temporary hidden files (e.g., .DS_Store on Mac or ~$filename.xlsx on Windows) while a file is being edited. You should filter these out:
def on_created(self, event):
if event.is_directory:
return
filename = os.path.basename(event.src_path)
if filename.startswith('.') or filename.startswith('~$'):
return # Ignore temp files
self.process_file(event.src_path)
3. How to Run it as a True Daemon
Running the script via python watcher_daemon.py works, but if you close the terminal, the process stops. Here are two ways to make it persistent:
Option A: Simple (Linux/macOS)
Use nohup to detach the process from the terminal and & to run it in the background.
nohup python3 watcher_daemon.py > output.log 2>&1 &
To stop it later, find the PID: ps aux | grep watcher_daemon.py and kill it.
Option B: Professional (Systemd)
If you are deploying on a Linux server, create a Systemd Service. This ensures the script starts on boot and restarts automatically if it crashes.
- Create a file at
/etc/systemd/system/filewatcher.service:
[Unit]
Description=Python File Watcher Daemon
After=network.target
[Service]
User=your_username
Group=your_username
WorkingDirectory=/home/your_username/your_project
ExecStart=/usr/bin/python3 /home/your_username/your_project/watcher_daemon.py
Restart=always
RestartSec=10
[Install]
WantedBy=multi-user.target
- Enable and start it:
sudo systemctl enable filewatcher
sudo systemctl start filewatcher