Created
May 23, 2013 14:55
-
-
Save reima/5636667 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Usage: watch.py [pattern] [command...] | |
# | |
# Watches files for changes and calls a command when a new file has been created | |
# or an existing file has been modified. A single % in the command will be | |
# replaced by the path of the created/modified file. | |
# | |
# Examples: | |
# watch.py *.tex pdflatex main.tex | |
# watch.py *.dot dot -Tpdf -O % | |
import glob | |
import os | |
import subprocess | |
import sys | |
import time | |
CHANGE_CREATED = 0 | |
CHANGE_DELETED = 1 | |
CHANGE_MODIFIED = 2 | |
def create_snapshot(pattern): | |
return {path: os.stat(path).st_mtime for path in glob.iglob(pattern)} | |
def compare_snapshots(prev, now): | |
changes = [] | |
for path in now: | |
if path not in prev: | |
changes.append((CHANGE_CREATED, path)) | |
elif prev[path] < now[path]: | |
changes.append((CHANGE_MODIFIED, path)) | |
for path in prev: | |
if path not in now: | |
changes.append((CHANGE_DELETED, path)) | |
return changes | |
pattern = sys.argv[1] | |
command = sys.argv[2:] | |
prev = create_snapshot(pattern) | |
while True: | |
time.sleep(1) | |
now = create_snapshot(pattern) | |
for change, path in compare_snapshots(prev, now): | |
if change == CHANGE_DELETED: | |
print('[DEL] ' + path) | |
elif change == CHANGE_CREATED: | |
print('[CRE] ' + path) | |
elif change == CHANGE_MODIFIED: | |
print('[MOD] ' + path) | |
if change == CHANGE_CREATED or change == CHANGE_MODIFIED: | |
c = [path if arg == '%' else arg for arg in command] | |
subprocess.call(c) | |
prev = now |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment