Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

Server.py:

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()
        self.stack.setCredentials(credentials)

    def start(self):
        self.stack.broadcastEvent(YowLayerEvent(YowNetworkLayer.EVENT_STATE_CONNECT))
        try:
            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...
        server.start()
        logging.info("Restarting..")

App.py:

import web

urls = (
  '/', 'index'
)

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

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

if __name__ == "__main__":
    app.run()

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?

like image 782
9gagger Avatar asked Sep 06 '16 13:09

9gagger


1 Answers

import thread

def run_app1():
    #something goes here

def run_app2():
    #something goes here


if __name__=='__main__':
    thread.start_new_thread(run_app1)
    thread.start_new_thread(run_app2)

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)
    t1.start()
    t2.start()

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.

like image 159
MooingRawr Avatar answered Oct 10 '22 15:10

MooingRawr