2015-11-14 04:57:02 +00:00
|
|
|
import os
|
2016-01-14 01:30:06 +00:00
|
|
|
import sys
|
2016-01-18 01:57:58 +00:00
|
|
|
from watchdog.events import RegexMatchingEventHandler
|
2016-01-14 01:30:06 +00:00
|
|
|
if sys.platform == 'darwin':
|
|
|
|
from watchdog.observers.polling import PollingObserver as Observer
|
|
|
|
else:
|
|
|
|
from watchdog.observers import Observer
|
2016-01-18 01:57:58 +00:00
|
|
|
# The OSX reloader is watchdog 0.8.3 breaks when unobserving paths.
|
|
|
|
# We use the PollingObserver instead.
|
2015-11-14 04:57:02 +00:00
|
|
|
|
|
|
|
_observers = {}
|
|
|
|
|
|
|
|
|
|
|
|
def watch(script, callback):
|
2015-11-26 13:59:54 +00:00
|
|
|
if script in _observers:
|
|
|
|
raise RuntimeError("Script already observed")
|
2015-11-14 04:57:02 +00:00
|
|
|
script_dir = os.path.dirname(os.path.abspath(script.args[0]))
|
2016-01-12 12:50:33 +00:00
|
|
|
script_name = os.path.basename(script.args[0])
|
|
|
|
event_handler = _ScriptModificationHandler(callback, filename=script_name)
|
2016-01-14 01:30:06 +00:00
|
|
|
observer = Observer()
|
2015-11-14 04:57:02 +00:00
|
|
|
observer.schedule(event_handler, script_dir)
|
|
|
|
observer.start()
|
|
|
|
_observers[script] = observer
|
|
|
|
|
|
|
|
|
|
|
|
def unwatch(script):
|
|
|
|
observer = _observers.pop(script, None)
|
|
|
|
if observer:
|
|
|
|
observer.stop()
|
2015-11-26 13:59:54 +00:00
|
|
|
observer.join()
|
2015-11-14 04:57:02 +00:00
|
|
|
|
|
|
|
|
2016-01-18 01:57:58 +00:00
|
|
|
class _ScriptModificationHandler(RegexMatchingEventHandler):
|
|
|
|
def __init__(self, callback, filename='.*'):
|
2016-01-12 14:24:18 +00:00
|
|
|
|
2015-11-14 04:57:02 +00:00
|
|
|
super(_ScriptModificationHandler, self).__init__(
|
|
|
|
ignore_directories=True,
|
2016-01-18 01:57:58 +00:00
|
|
|
regexes=['.*'+filename]
|
2015-11-14 04:57:02 +00:00
|
|
|
)
|
|
|
|
self.callback = callback
|
2016-01-12 12:50:33 +00:00
|
|
|
self.filename = filename
|
2015-11-14 04:57:02 +00:00
|
|
|
|
|
|
|
def on_modified(self, event):
|
2016-01-18 01:57:58 +00:00
|
|
|
self.callback()
|
2016-01-12 03:45:03 +00:00
|
|
|
|
|
|
|
__all__ = ["watch", "unwatch"]
|
2015-11-14 04:57:02 +00:00
|
|
|
|