Skip to content

Instantly share code, notes, and snippets.

@Flushot
Created August 11, 2017 04:04
Show Gist options
  • Save Flushot/85b6c95398ed95899e214fa8a671e0cd to your computer and use it in GitHub Desktop.
Save Flushot/85b6c95398ed95899e214fa8a671e0cd to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
from __future__ import absolute_import, print_function, unicode_literals, division
import re
import logging
import threading
import time
import watchdog.events
import watchdog.observers
from IPython.lib.deepreload import reload as dreload
from . import utils, boot
log = logging.getLogger(__name__)
class ChangeDetector(watchdog.events.FileSystemEventHandler):
def __init__(self, change_event):
super(ChangeDetector, self).__init__()
self._change_event = change_event
def on_modified(self, event):
if re.search(r'\.(py|ini|conf)$', event.src_path) is not None:
log.info("Reloading because of file change: {}".format(event.src_path))
self._change_event.set()
class ServerThread(threading.Thread):
def __init__(self, change_event):
super(ServerThread, self).__init__()
self._change_event = change_event
self.running = False
def run(self):
self.running = True
while self.running:
# Start server
print('Starting...')
server = boot.main(serve_forever=False)
server.start()
# Wait for change
self._change_event.wait()
self._change_event.clear()
# Reload server
print('Stopping...')
server.stop(timeout=10)
dreload(boot)
if __name__ == '__main__':
change_event = threading.Event()
change_detector = ChangeDetector(change_event)
server_thread = ServerThread(change_event)
server_thread.start()
observer = watchdog.observers.Observer()
observer.schedule(change_detector, utils.get_package_root_path(), recursive=True)
observer.start()
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
print('Terminated')
observer.stop()
server_thread.running = False
change_event.set()
observer.join()
server_thread.join()
raise SystemExit(0)
##
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment