9gager 9gager - 4 months ago 27
Python Question

Run multiple servers in python at same time (Threading)

I have 2 servers in python, I want to mix them up in one single .py and run together:


import logging, time, os, sys
from yowsup.layers import YowLayerEvent, YowParallelLayer
from yowsup.layers.auth import AuthError
from yowsup.layers.network import YowNetworkLayer
from yowsup.stacks.yowstack import YowStackBuilder

from layers.notifications.notification_layer import NotificationsLayer
from router import RouteLayer

class YowsupEchoStack(object):
def __init__(self, credentials):
"Creates the stacks of the Yowsup Server,"
self.credentials = credentials
stack_builder = YowStackBuilder().pushDefaultLayers(True)

stack_builder.push(YowParallelLayer([RouteLayer, NotificationsLayer]))
self.stack = stack_builder.build()

def start(self):
logging.info("#" * 50)
logging.info("\tServer started. Phone number: %s" % self.credentials[0])
logging.info("#" * 50)
self.stack.loop(timeout=0.5, discrete=0.5)
except AuthError as e:
logging.exception("Authentication Error: %s" % e.message)
if "<xml-not-well-formed>" in str(e):
os.execl(sys.executable, sys.executable, *sys.argv)
except Exception as e:
logging.exception("Unexpected Exception: %s" % e.message)

if __name__ == "__main__":
import sys
import config

logging.basicConfig(stream=sys.stdout, level=config.logging_level, format=config.log_format)
server = YowsupEchoStack(config.auth)
while True:
# In case of disconnect, keeps connecting...


import web

urls = (
'/', 'index'

app = web.application(urls, globals())

class index:
def GET(self):
greeting = "Hello World"
return greeting

if __name__ == "__main__":

I want to run both together from single .py file together.
If I try to run them from one file, either of the both starts and other one starts only when first one is done working.

How can I run 2 servers in python together?

import thread

def run_app1():
    #something goes here

def run_app2():
    #something goes here

if __name__=='__main__':

if you need to pass args to the functions you can do:

thread.start_new_thread(run_app1, (arg1,arg2,....))

if you want more control in your threads you could go:

import threading
def app1():
    #something here

def app2():
    #something here

if __name__=='__main__':
    t1 = threading.Thread(target=app1)
    t2 = threading.Thread(target=app2)

if you need to pass args you can go:

t1 = threading.Thread(target=app1, args=(arg1,arg2,arg3.....))

What's the differences between thread vs threading? Threading is higher level module than thread and in 3.x thread got renamed to _thread... more info here: http://docs.python.org/library/threading.html but that's for another question I guess.

So in your case, just make a function that runs the first script, and the second script, and just spawn threads to run them.