Skip to content

Instantly share code, notes, and snippets.

@mariosv
Last active August 29, 2015 13:56
Show Gist options
  • Save mariosv/8820150 to your computer and use it in GitHub Desktop.
Save mariosv/8820150 to your computer and use it in GitHub Desktop.
Script to monitor file modifications and run commands
#!/usr/bin/env python
""" Monitors modifications of files with the given file extensions
recursively under the current directory and runs the supplied command.
Usage:
monitor_and_run <cmd> <ext1> [[ext2]...]
For example:
monitor_and_run make .tex
will monitor LaTeX files under the current directory and run 'make'
when one of them is modified
"""
import os
import sys
import os.path
from subprocess import call
from pyinotify import WatchManager, Notifier, ProcessEvent, IN_MODIFY
if len(sys.argv) < 3:
sys.stderr.write('Invalid arguments.\n\tUsage: %s <cmd> <file extension1> '
'[[file extensio2]...]\n' % sys.argv[0])
sys.exit(1)
cmd = sys.argv[1]
monitored_file_extensions = sys.argv[2:]
wm = WatchManager()
mask = IN_MODIFY
class Handler(ProcessEvent):
def process_IN_MODIFY(self, evt):
extension = os.path.splitext(evt.name)
if extension[1] in monitored_file_extensions:
call(cmd)
notifier = Notifier(wm, Handler())
watch = wm.add_watch('.', mask, rec=True)
while True:
try:
notifier.process_events()
if notifier.check_events():
notifier.read_events()
except KeyboardInterrupt:
notifier.stop()
break
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment