20 Feb

Watching specified files/folders for changes in Python

For specific purposes there could be a need to monitor file and folders changes on Linux box. To achieve this you can go with incrond. There’s also Pythonic way. Several Python wrappers on inotify feature  are accessible. Here we’ll cover simple Python daemon Watcher (github repo). First of all, we need to install python-inotify package:

yum install python-inotify.noarch

python-inotify uses Linux kernel feature called inotify (accessible starting from version 2.6.13). It allows to get notifications on file system event from user-space.

Now you can download last version of the config and the daemon:

mkdir watcher
cd watcher
wget https://raw.github.com/splitbrain/Watcher/master/watcher.ini
wget https://raw.github.com/splitbrain/Watcher/master/watcher.py

Modify your watcher.ini to meet your requirements:

[DEFAULT]
logfile=/tmp/watcher.log
pidfile=/tmp/watcher.pid
[job1]
watch=/tmp
events=create,delete
recursive=false
autoadd=true
command=ls -l $filename

Now you are ready to start Watcher daemon:

chmod u+x watcher.py
./watcher.py -c watcher.ini debug