2015-11-14 04:57:02 +00:00
|
|
|
import os
|
2016-01-12 03:45:03 +00:00
|
|
|
import fnmatch
|
2015-11-14 04:57:02 +00:00
|
|
|
from watchdog.events import PatternMatchingEventHandler
|
2016-01-12 13:36:59 +00:00
|
|
|
from watchdog.observers.polling import PollingObserver
|
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-12 13:36:59 +00:00
|
|
|
observer = PollingObserver()
|
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
|
|
|
|
|
|
|
|
|
|
|
class _ScriptModificationHandler(PatternMatchingEventHandler):
|
2016-01-12 12:50:33 +00:00
|
|
|
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,
|
|
|
|
)
|
|
|
|
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-12 03:45:03 +00:00
|
|
|
if event.is_directory:
|
2016-01-12 14:24:18 +00:00
|
|
|
files_in_dir = [event.src_path + "/" +
|
2016-01-12 03:45:03 +00:00
|
|
|
f for f in os.listdir(event.src_path)]
|
|
|
|
if len(files_in_dir) > 0:
|
2016-01-12 12:50:33 +00:00
|
|
|
modified_filepath = max(files_in_dir, key=os.path.getmtime)
|
2016-01-12 03:45:03 +00:00
|
|
|
else:
|
|
|
|
return
|
|
|
|
else:
|
2016-01-12 12:50:33 +00:00
|
|
|
modified_filepath = event.src_path
|
2016-01-12 03:45:03 +00:00
|
|
|
|
2016-01-12 13:36:59 +00:00
|
|
|
if fnmatch.fnmatch(os.path.basename(modified_filepath), self.filename):
|
2016-01-12 03:45:03 +00:00
|
|
|
self.callback()
|
|
|
|
|
2016-01-12 14:24:18 +00:00
|
|
|
def on_created(self, event):
|
|
|
|
if fnmatch.fnmatch(os.path.basename(event.src_path), self.filename):
|
|
|
|
self.callback()
|
|
|
|
|
2016-01-12 03:45:03 +00:00
|
|
|
__all__ = ["watch", "unwatch"]
|
2015-11-14 04:57:02 +00:00
|
|
|
|