|
| 1 | +#!/usr/bin/env python |
| 2 | +# -*- coding: utf-8 -*- |
| 3 | + |
| 4 | +__author__ = 'Michael Liao' |
| 5 | + |
| 6 | +import os, sys, time, subprocess |
| 7 | + |
| 8 | +from watchdog.observers import Observer |
| 9 | +from watchdog.events import FileSystemEventHandler |
| 10 | + |
| 11 | +def log(s): |
| 12 | + print '[Monitor] %s' % s |
| 13 | + |
| 14 | +class MyFileSystemEventHander(FileSystemEventHandler): |
| 15 | + |
| 16 | + def __init__(self, fn): |
| 17 | + super(MyFileSystemEventHander, self).__init__() |
| 18 | + self.restart = fn |
| 19 | + |
| 20 | + def on_any_event(self, event): |
| 21 | + if event.src_path.endswith('.py'): |
| 22 | + log('Python source file changed: %s' % event.src_path) |
| 23 | + self.restart() |
| 24 | + |
| 25 | +command = ['echo', 'ok'] |
| 26 | +process = None |
| 27 | + |
| 28 | +def kill_process(): |
| 29 | + global process |
| 30 | + if process: |
| 31 | + log('Kill process [%s]...' % process.pid) |
| 32 | + process.kill() |
| 33 | + process.wait() |
| 34 | + log('Process ended with code %s.' % process.returncode) |
| 35 | + process = None |
| 36 | + |
| 37 | +def start_process(): |
| 38 | + global process, command |
| 39 | + log('Start process %s...' % ' '.join(command)) |
| 40 | + process = subprocess.Popen(command, stdin=sys.stdin, stdout=sys.stdout, stderr=sys.stderr) |
| 41 | + |
| 42 | +def restart_process(): |
| 43 | + kill_process() |
| 44 | + start_process() |
| 45 | + |
| 46 | +def start_watch(path, callback): |
| 47 | + observer = Observer() |
| 48 | + observer.schedule(MyFileSystemEventHander(restart_process), path, recursive=True) |
| 49 | + observer.start() |
| 50 | + log('Watching directory %s...' % path) |
| 51 | + start_process() |
| 52 | + try: |
| 53 | + while True: |
| 54 | + time.sleep(0.5) |
| 55 | + except KeyboardInterrupt: |
| 56 | + observer.stop() |
| 57 | + observer.join() |
| 58 | + |
| 59 | +if __name__ == '__main__': |
| 60 | + argv = sys.argv[1:] |
| 61 | + if not argv: |
| 62 | + print('Usage: ./pymonitor your-script.py') |
| 63 | + exit(0) |
| 64 | + if argv[0]!='python': |
| 65 | + argv.insert(0, 'python') |
| 66 | + command = argv |
| 67 | + path = os.path.abspath('.') |
| 68 | + start_watch(path, None) |
0 commit comments