Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Fetching contributors…

Cannot retrieve contributors at this time

file 62 lines (45 sloc) 1.241 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
"""
Watch a bunch of files and run a command if any changes are detected.

Usage
-----
::

python watcher.py 'echo changes' one.py two.py

To automatically keep Sphinx docs up to date::

python watcher.py 'make html' $(find . -name '*.rst')

Problems
--------

* The file checking would be way more efficient using inotify or whatever the
equivalent is on OS X.
* It doesn't handle bad input or spaces in filenames.

But it works for me.
"""
import os
import sys
import time


_mtimes = {}


def timecheck(files):
    """Return True if any of the files have changed."""
    global _mtimes
    for filename in files:
        mtime = os.stat(filename).st_mtime
        if filename not in _mtimes:
            _mtimes[filename] = mtime
        elif mtime != _mtimes[filename]:
            _mtimes = {}
            return True
    else:
        return False


def watcher(command, files):
    """Run ``command`` if any file in ``files`` changes."""
    while True:
        if timecheck(files):
            os.system(command)
        time.sleep(1)


def main():
    command, files = sys.argv[1], sys.argv[2:]
    try:
        watcher(command, files)
    except KeyboardInterrupt:
        pass


if __name__ == '__main__':
    main()
Something went wrong with that request. Please try again.