Created
October 31, 2012 15:49
-
-
Save Yukilas/3987809 to your computer and use it in GitHub Desktop.
[Django, Gevent, SocketIO] Run script to automatically restart Gunicorn when a change is made on a python file
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# -*- coding:Utf-8 -*- | |
import os | |
import shlex | |
import subprocess | |
import sys | |
import time | |
from watchdog.events import FileSystemEventHandler | |
from watchdog.observers import Observer | |
class GunicornEventHandler(FileSystemEventHandler): | |
""" | |
Restart the gunicorn process when an event is captured. | |
""" | |
def __init__(self, *args, **kwargs): | |
super(GunicornEventHandler, self).__init__(*args, **kwargs) | |
self.pid = None | |
self.pid_file = "/tmp/gunicorn.pid" | |
self.worker_class = "socketio.sgunicorn.GeventSocketIOWorker" | |
def get_start_cmd(self): | |
return "python manage.py run_gunicorn --worker-class {0} --pid {1}".format( | |
self.worker_class, self.pid_file) | |
def on_any_event(self, event): | |
super(GunicornEventHandler, self).on_any_event(event) | |
#Do the action only for python files | |
if event is not None and event.src_path[-3:] != ".py": | |
return | |
if self.pid: | |
os.kill(self.pid, 9) | |
time.sleep(1) | |
p = subprocess.Popen(shlex.split(self.get_start_cmd())) | |
self.pid = p.pid | |
if __name__ == "__main__": | |
path = sys.argv[1] if len(sys.argv) > 1 else "." | |
handler = GunicornEventHandler() | |
observer = Observer() | |
observer.schedule(handler, path, recursive=True) | |
observer.start() | |
#Triggers an event in order to initially launch the server | |
handler.on_any_event(None) | |
try: | |
while True: | |
time.sleep(1) | |
except KeyboardInterrupt: | |
observer.stop() | |
observer.join() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks, works great