inotify-simple

2.0.1 · active · verified Sun Apr 12

inotify-simple is a lightweight Python wrapper around the Linux `inotify` API, implemented using `ctypes`. It provides a direct, low-level interface to filesystem events without much abstraction, making it efficient and close to the kernel's behavior. The library is currently at version 2.0.1 and is actively maintained with a stable release cadence.

Warnings

Install

Imports

Quickstart

This example demonstrates how to set up a basic `inotify` watch on a directory for creation, deletion, modification, and close-write events. It then continuously reads and prints detected events. It also shows how to gracefully stop the monitoring and clean up resources.

import os
import time
from inotify_simple import INotify, flags

# Create a temporary directory to watch
watch_dir = '/tmp/inotify_test_simple'
os.makedirs(watch_dir, exist_ok=True)

inotify = INotify()

# Add a watch for create, delete, and modify events
# flags.CLOSE_WRITE is often useful for 'file saved' events
watch_flags = flags.CREATE | flags.DELETE | flags.MODIFY | flags.CLOSE_WRITE
wd = inotify.add_watch(watch_dir, watch_flags)

print(f"Watching directory: {watch_dir} (watch descriptor: {wd})")
print("Create, modify, or delete files in this directory. Press Ctrl+C to exit.")

try:
    while True:
        # Read events with a timeout (e.g., 1000 ms = 1 second)
        # Events are returned as a list of namedtuple objects
        events = inotify.read(timeout=1000)
        if not events:
            # print("No events in the last second.") # Uncomment for verbose output
            continue

        for event in events:
            print(f"Event: wd={event.wd}, mask={event.mask} ({flags.from_mask(event.mask)}), cookie={event.cookie}, name='{event.name}'")

            # Example: react to a file creation
            if flags.CREATE in flags.from_mask(event.mask):
                print(f"  New file/directory created: {os.path.join(watch_dir, event.name)}")
            if flags.DELETE in flags.from_mask(event.mask):
                print(f"  File/directory deleted: {os.path.join(watch_dir, event.name)}")
            if flags.CLOSE_WRITE in flags.from_mask(event.mask):
                print(f"  File written and closed: {os.path.join(watch_dir, event.name)}")

except KeyboardInterrupt:
    print("Monitoring stopped.")
finally:
    inotify.rm_watch(wd)
    inotify.close()
    # Clean up the temporary directory
    # os.rmdir(watch_dir) # Only if empty
    print(f"Removed watch for {watch_dir} and closed inotify instance.")

view raw JSON →