PyInotify
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
- gotcha This library is an adapter to the Linux kernel's inotify interface and is therefore Linux-specific. It will not work on other operating systems like Windows or macOS.
- gotcha The inotify event queue has a finite size. If events are generated faster than they can be processed, the queue can overflow, leading to missed events. This is a kernel limitation, not specific to PyInotify.
- gotcha Watching certain system directories (e.g., `/proc`, `/sys`, or root `/`) may require elevated permissions (root) or specific capabilities, and can generate a very high volume of events, impacting performance.
- breaking Prior to version 0.2.x, the library's API was lower-level and involved directly interacting with `inotify.watcher`. Version 0.2.x introduced the `inotify.adapters` module, which provides a higher-level, more user-friendly interface. Code written for 0.1.x will not be directly compatible with 0.2.x+.
Install
-
pip install inotify
Imports
- Inotify
from inotify import Inotify
from inotify.adapters import Inotify
Quickstart
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)