Skip to content

Instantly share code, notes, and snippets.

@benozol
Created May 4, 2010 12:07
Show Gist options
  • Save benozol/389332 to your computer and use it in GitHub Desktop.
Save benozol/389332 to your computer and use it in GitHub Desktop.
#!/usr/bin/python
# Monitors file changes and runs programs on them.
# Needs pyinotifyx.
import os, sys, subprocess
from inotifyx import init, add_watch, IN_CLOSE_WRITE, get_events, rm_watch
help_text="""\
This program monitors some files and runs some commands if one is modified.
For example, to interactively view the pdf of a latex file, start:
$ onchange.py *.tex -- latex %f
%f in the commands is replaced by the modified filename, %b with its basename.
It is possible to state several files to watch. Likewise, several commands can be stated, they are executed successively until one fails.
Synopsis
""" + "$ %s file1 ... -- command1 ..."%sys.argv[0]
if __name__ == "__main__":
if "--" not in sys.argv:
print help_text
sys.exit(1)
minus_ix = sys.argv.index("--")
filenames = sys.argv[1:minus_ix]
commands = sys.argv[minus_ix+1:]
print
print "Filenames:", ", ".join(filenames)
print "Commands: ", ", ".join(commands)
filedict = {}
fd = init()
def add_watch_to_file_dict(filename, wd=None):
if wd and wd in filedict:
del filedict[wd]
filedict[add_watch(fd, filename, IN_CLOSE_WRITE)] = filename
try:
for filename in filenames:
add_watch_to_file_dict(filename)
while 1:
for event in get_events(fd):
print 80 * '-'
filename = filedict[event.wd]
print "--", filename
(basename, ext) = os.path.splitext(filename)
for cmd in commands:
filled_cmd = cmd.replace('%f', filename).replace('%b', basename)
print ">>", filled_cmd
sp = subprocess.Popen(filled_cmd, shell=True,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output = sp.stdout.read() + sp.stderr.read()
if sp.wait() > 0:
subprocess.call(["kdialog", "--error", output])
break
add_watch_to_file_dict(filename, event.wd)
except KeyboardInterrupt:
pass
finally:
for wd in filedict:
try: rm_watch(fd, wd)
except: pass
os.close(fd)
@benozol
Copy link
Author

benozol commented May 4, 2010

This program monitors some files and runs some commands if one is modified.
For example, to interactively view the pdf of a freemind mindmap, start:
$ onchange *.tex -- latex --jobname=%b %f
%f in the commands is replaced by the modified filename, %b with its basename.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment