在Python中同时运行多个服务器(线程)

6
我有两个Python服务器,想将它们合并到一个.py文件中一起运行。

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()

我希望您能够从单个.py文件中同时运行两个程序。如果我尝试从一个文件中运行它们,其中一个开始工作时,只有在第一个程序完成工作后,另一个程序才会开始工作。
如何在Python中同时运行2个服务器?

你有考虑过线程吗? - MooingRawr
不是...我想要关于线程的帮助...那才是我的意思。 - 9gagger
1个回答

9
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)

如果您需要将参数传递给函数,可以这样做:
thread.start_new_thread(run_app1, (arg1,arg2,....))

如果您想在线程中拥有更多的控制权,可以选择以下方法:

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()

如果需要传递参数,可以这样做:
t1 = threading.Thread(target=app1, args=(arg1,arg2,arg3.....))

有关thread和threading的区别是什么?Threading模块比thread模块更高级,在3.x版本中,thread模块被重命名为_thread……更多信息请参见http://docs.python.org/library/threading.html,但我想这是另一个问题。因此,在您的情况下,只需创建一个运行第一个脚本和第二个脚本的函数,并生成线程来运行它们。

太棒了!!非常感谢,汪汪。狗狗军团向您致敬。 - 9gagger

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接