$ python autocmd.py /exam/ple .txt,.html /pri/vate some_script.pl
Advantages:
autocmd.py:
#!/usr/bin/env python
"""autocmd.py
Adopted from autocompile.py [1] example.
[1] http://git.dbzteam.org/pyinotify/tree/examples/autocompile.py
Dependencies:
Linux, Python, pyinotify
"""
import os, shutil, subprocess, sys
import pyinotify
from pyinotify import log
class Handler(pyinotify.ProcessEvent):
def my_init(self, **kwargs):
self.__dict__.update(kwargs)
def process_IN_CLOSE_WRITE(self, event):
# file was closed, ready to move it
if event.dir or os.path.splitext(event.name)[1] not in self.extensions:
# directory or file with uninteresting extension
return # do nothing
try:
log.debug('==> moving %s' % event.name)
shutil.move(event.pathname, os.path.join(self.destdir, event.name))
cmd = self.cmd + [event.name]
log.debug("==> calling %s in %s" % (cmd, self.destdir))
subprocess.call(cmd, cwd=self.destdir)
except (IOError, OSError, shutil.Error), e:
log.error(e)
def process_default(self, event):
pass
def mainloop(path, handler):
wm = pyinotify.WatchManager()
notifier = pyinotify.Notifier(wm, default_proc_fun=handler)
wm.add_watch(path, pyinotify.ALL_EVENTS, rec=True, auto_add=True)
log.debug('==> Start monitoring %s (type c^c to exit)' % path)
notifier.loop()
if __name__ == '__main__':
if len(sys.argv) < 5:
print >> sys.stderr, "USAGE: %s dir ext[,ext].. destdir cmd [args].." % (
os.path.basename(sys.argv[0]),)
sys.exit(2)
path = sys.argv[1] # dir to monitor
extensions = set(sys.argv[2].split(','))
destdir = sys.argv[3]
cmd = sys.argv[4:]
log.setLevel(10) # verbose
# Blocks monitoring
mainloop(path, Handler(path=path, destdir=destdir, cmd=cmd,
extensions=extensions))