Created
February 18, 2013 04:30
-
-
Save mitgr81/4975131 to your computer and use it in GitHub Desktop.
Just a little scriptlet that runs a frontend (in this case, node) web server alongside a backend (in this case, python) server. This should not be used in production unless otherwise proven.
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 | |
import subprocess | |
import socket | |
from multiprocessing import Process | |
import sys | |
if sys.version_info < (3,): | |
range = xrange | |
BIND_IP = '0.0.0.0' | |
processes = [] | |
def get_port(): | |
start_port = 5000 | |
end_port = 6000 | |
def test_bind(port): | |
""" Test a bind to the given socket so we can make run more gooder, 'influenced' from werkzeug's bind_simple """ | |
test_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) | |
test_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) | |
test_socket.bind((BIND_IP, port)) | |
test_socket.close() | |
for portnum in range(start_port, end_port, 2): | |
try: | |
test_bind(portnum) | |
test_bind(portnum + 1) | |
return portnum | |
except socket.error: | |
pass | |
raise Exception("No port is open between {} and {}, try something else?".format(start_port, end_port)) | |
def watch_process(command_list): | |
process = subprocess.Popen(command_list, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) | |
try: | |
# Poll process for new output until finished | |
while True: | |
nextline = process.stdout.readline() | |
if nextline == '' and process.poll() != None: | |
break | |
sys.stdout.write(nextline) | |
sys.stdout.flush() | |
except: | |
#exit without garbaging up my garbage | |
pass | |
def start_backend(portnum): | |
print("Starting Flask at port {}".format(portnum)) | |
watch_process(['python', 'backend.py', str(portnum)]) | |
def start_frontend(portnum): | |
print("Starting Express at port {}".format(portnum)) | |
watch_process(['node', 'frontend.js', str(portnum)]) | |
if __name__ == '__main__': | |
port = get_port() | |
p = Process(target=start_backend, args=(port,)) | |
p.deamon = True | |
p.start() | |
p1 = Process(target=start_frontend, args=(port + 1,)) | |
p1.deamon = True | |
p1.start() | |
try: | |
p.join() | |
p1.join() | |
except KeyboardInterrupt: | |
print("\rWe understand that you have a choice when running servers and are thrilled that you chose SERVERNAMEHERE. Shutting down now!") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment