Skip to content

@zed /autocmd.py
Created

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
#!/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))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.