Skip to content

Instantly share code, notes, and snippets.

@krha
Forked from yy/monex.py
Last active August 29, 2015 14:07
Show Gist options
  • Save krha/9cef20f7e37ad316d3fa to your computer and use it in GitHub Desktop.
Save krha/9cef20f7e37ad316d3fa to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
# encoding: utf-8
"""
MONitor & EXecute
Yong-Yeol Ahn (http://yongyeol.com/)
This script monitors multiple files and executes the given command when
any of those files is changed.
"""
import sys
import os
import time
import subprocess
from glob import glob
from optparse import OptionParser
from itertools import izip
def do(command):
_PIPE = subprocess.PIPE
p = subprocess.Popen(command.split(" "), close_fds=True, shell=True, stdin=_PIPE, stdout=_PIPE, stderr=_PIPE)
(out, err) = p.communicate(input=None)
if p.returncode is not 0:
print out + '\n' + err
else:
print '%s\tDone (%s).' % (time.strftime('%X %x %Z'), command)
def get_filelist(args):
files = set()
for arg in args:
files |= set(glob(arg))
return sorted(files)
if __name__=='__main__':
usage = 'usage: %prog -c "command" file1 file2 ...'
parser = OptionParser(usage=usage)
parser.add_option("-c", "--command", dest='command',
help="command to be executed")
(options, args) = parser.parse_args()
if not options.command:
parser.error('-c option is needed')
command = options.command.strip('"')
files = get_filelist(args)
print 'monitoring the following files...'
print '\n'.join(files)
time.sleep(2)
old_timestamps = [os.stat(x).st_mtime for x in files]
do(command)
while(True):
curr_timestamps = [os.stat(x).st_mtime for x in files]
if any(curr != old for curr, old in izip(curr_timestamps, old_timestamps)):
do(command)
old_timestamps = curr_timestamps
else:
time.sleep(1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment