Pelicanux

Just A Few Random Words

Python Inotify

This will be quite a brief post, as I didn’t spend too much time on the subject. Nevertheless, I like the possibilities given by inotify, and I wanted to write a few words on this.

Inotify is a tool letting Sysadmins monitoring their servers filesystems. It relies on the select system call. An action gets triggered whenever a change occurs in a part of filesystem.

This can, for instance, be really useful when a scripts must be launched when files got uploaded on server. The alternative being launching a cron every minutes (Yyak :/). Here, a lock is setup on a folder, and it will trigger an action (files treatment) when, and only when, these files will appear.

It is packaged on debian (inotify-tools package) and on most Linux distributions.

Python gets its own implementation Documentation here.

Here is a script adapted from this documentation:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#!/usr/bin/env python

import os
import sys
import pyinotify

class EventHandler(pyinotify.ProcessEvent):

   def process_IN_CLOSE_WRITE(self, event):
      with open('/tmp/log', 'a') as f:
         f.write('ICI:'+str(event.pathname)+'\n')

wm = pyinotify.WatchManager()
handler = EventHandler()

notifier = pyinotify.Notifier(
   wm,
   handler,
)

wdd = wm.add_watch(
   '/tmp/notifier/files',
   pyinotify.IN_CLOSE_WRITE,
   rec=True,
)

if os.fork():
   sys.exit(0)

notifier.loop()

Hoping it will be of some help!