mitmproxy/libmproxy/script/reloader.py

55 lines
1.7 KiB
Python
Raw Normal View History

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
from watchdog.observers import Observer
_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]))
event_handler = _ScriptModificationHandler(callback)
observer = Observer()
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 03:45:03 +00:00
def __init__(self, callback, pattern='*.py'):
2015-11-14 04:57:02 +00:00
# We could enumerate all relevant *.py files (as werkzeug does it),
# but our case looks like it isn't as simple as enumerating sys.modules.
# This should be good enough for now.
super(_ScriptModificationHandler, self).__init__(
ignore_directories=True,
)
self.callback = callback
2016-01-12 03:45:03 +00:00
self.pattern = pattern
2015-11-14 04:57:02 +00:00
def on_modified(self, event):
2016-01-12 03:45:03 +00:00
super(_ScriptModificationHandler, self).on_modified(event)
if event.is_directory:
files_in_dir = [event.src_path + "/" + \
f for f in os.listdir(event.src_path)]
if len(files_in_dir) > 0:
modifiedFilename = max(files_in_dir, key=os.path.getmtime)
else:
return
else:
modifiedFilename = event.src_path
if fnmatch.fnmatch(os.path.basename(modifiedFilename), self.pattern):
self.callback()
__all__ = ["watch", "unwatch"]
2015-11-14 04:57:02 +00:00