PyInotify

0.2.12 · active · verified Wed Apr 15

PyInotify is a Python adapter to the Linux kernel's inotify directory-watching interface. It provides a simple and efficient way to monitor filesystem events like file creation, deletion, modification, and access. The current version is 0.2.12, with releases typically occurring as needed for bug fixes or minor enhancements.

Warnings

Install

Imports

Quickstart

This example demonstrates how to set up a watch on a directory and print detected filesystem events. It creates a temporary directory, adds a recursive watch for all event types, and then continuously listens for events. It handles graceful shutdown and cleans up the temporary directory.

import os
import time
from inotify.adapters import Inotify

# Create a temporary directory for demonstration
test_dir = "./inotify_test_dir"
if not os.path.exists(test_dir):
    os.makedirs(test_dir)

# Initialize inotify adapter
i = Inotify()

# Add a watch for the directory and its subdirectories
# mask=Inotify.ALL_EVENTS covers most common operations
i.add_watch(test_dir, mask=Inotify.ALL_EVENTS)

print(f"Watching directory: {test_dir} for all events...")
print("Try creating, modifying, or deleting files/directories inside it.")
print("Press Ctrl+C to stop.")

try:
    # event_gen yields (event_tuple) or None if yield_nones=True
    # A tuple typically contains (wd, mask, cookie, name).
    # The adapter enhances this to (header, type_names, path, filename)
    for event in i.event_gen(yield_nones=False):
        (_, type_names, path, filename) = event
        print(f"Event detected: TYPE={type_names}, PATH={path}, FILENAME={filename}")
except KeyboardInterrupt:
    print("\nStopping inotify watch.")
finally:
    # Always remove the watch when done
    i.remove_watch(test_dir)
    # Clean up the test directory
    if os.path.exists(test_dir):
        for root, dirs, files in os.walk(test_dir, topdown=False):
            for name in files:
                os.remove(os.path.join(root, name))
            for name in dirs:
                os.rmdir(os.path.join(root, name))
        os.rmdir(test_dir)

view raw JSON →