gitmyhub

watchdog

Python ★ 7.4k updated 2d ago

Python library and shell utilities to monitor filesystem events.

A Python library and CLI tool that watches directories for file changes and automatically runs your code in response, supporting Linux, macOS, Windows, and FreeBSD with a 15-line setup.

PythoninotifyFSEventskqueueYAMLsetup: easycomplexity 2/5

Watchdog is a Python library and command-line tool that watches directories for file changes and runs code in response. When a file is created, modified, moved, or deleted, watchdog notices and can trigger any action you define. Developers use it to auto-reload servers when code changes, run tests when source files save, or copy files whenever they are updated.

Using it from Python involves creating an event handler class with methods that get called when specific events occur, then starting an Observer that monitors a directory. The observer can watch recursively, meaning changes in subdirectories trigger events as well. A code example in the README shows the full setup takes about fifteen lines of Python.

The library also ships with an optional command-line utility called watchmedo. Without writing any Python, you can use watchmedo to log all file events in a directory, run shell commands when files matching a pattern change, or define complex automation through a YAML configuration file called tricks.yaml. The tricks system lets plugin authors write reusable event handlers that other users can reference by class name in their YAML config.

Watchdog works on Linux using inotify, on macOS using FSEvents or kqueue, on FreeBSD using kqueue, and on Windows using the ReadDirectoryChangesW interface. A slower polling fallback is available for environments where none of those are accessible. The README notes a few edge cases: monitoring very large directory trees with kqueue requires increasing the operating system file descriptor limit, and editors like Vim that use backup files for saving may not trigger the expected modification events.

Install with pip using pip install watchdog or pip install 'watchdog[watchmedo]' to include the CLI tool. Python 3.9 or higher is required. The project is licensed under the Apache License 2.0.

Where it fits