pywatchman
pywatchman is a Python client library for Facebook's Watchman file watching service. It provides a simple interface to connect to and query the Watchman daemon to efficiently discover file system changes. The library is actively maintained with frequent development tags on GitHub, and new PyPI releases (currently 3.0.0) are made periodically.
Warnings
- gotcha pywatchman is a client library and requires the separate Watchman daemon to be installed and running on your system. It is not a standalone file watcher written purely in Python.
- breaking Older versions of pywatchman (specifically 1.4.1) were known to raise a `SystemError` on Python 3.10+ due to issues with internal C extensions related to the `PY_SSIZE_T_CLEAN` macro.
- gotcha Dedicated documentation for the pywatchman Python API is limited. Users often need to refer to the Watchman daemon's general command documentation and the pywatchman source code for detailed usage examples and API specifics.
- gotcha Issues have been reported where `ignore_dirs` in the `.watchmanconfig` file are not always respected by `WatchmanReloader` integrations (e.g., in Django), leading to excessive file watching in ignored paths like virtual environments or system Python directories.
Install
-
pip install pywatchman
Imports
- client
from watchman_client import Client
import pywatchman client = pywatchman.client()
- bser
from pywatchman import bser
Quickstart
import pywatchman
import os
def main():
try:
# Establish a connection to the Watchman daemon
client = pywatchman.client()
print(f"Connected to Watchman: {client.query('get-sockname')['sockname']}")
# Define the directory to watch (current directory for example)
watch_dir = os.getcwd()
print(f"Attempting to watch directory: {watch_dir}")
# Tell Watchman to start watching the directory
# This will return existing watch if already present
watch_result = client.query('watch', watch_dir)
print(f"Watch established: {watch_result}")
# Perform a query for Python files that have changed since the last clock
# The 'clock' value is automatically managed by Watchman
query_result = client.query(
'query', watch_dir, {
'expression': ['allof', ['type', 'f'], ['suffix', 'py']],
'fields': ['name', 'size', 'mtime_ms']
}
)
print("\nRecently changed Python files:")
for f in query_result.get('files', []):
print(f" - {f['name']} (size: {f['size']} bytes, modified: {f['mtime_ms']}ms ago)")
except pywatchman.Unavailable as e:
print(f"Error: Watchman service is unavailable. Please ensure Watchman is installed and running. Details: {e}")
except Exception as e:
print(f"An unexpected error occurred: {e}")
if __name__ == '__main__':
main()