public
Last active

  • Download Gist
autocmd.py
Python
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 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
#!/usr/bin/env python
"""$ python autocmd.py /exam/ple .txt,.html /pri/vate some_script.pl
 
Answer for http://stackoverflow.com/questions/1533923/monitor-folder-for-new-files-using-unix-ksh-shell-script-or-perl-script-and-trigg
 
Adopted from autocompile.py [1] example.
 
[1] http://git.dbzteam.org/pyinotify/tree/examples/autocompile.py
 
Advantages:
 
- easier to install than ``inocron`` due to pyinotify is pure Python
- event-driven -- less impact than the perl script
 
Dependencies:
 
Linux, Python
"""
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 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))

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.