首页 > 解决方案 > 从同一个脚本 Python 运行 2 个 web.py 服务器

问题描述

Python 新手。我正在尝试在同一脚本上运行 2 个具有不同端口的 web.py 服务器。基本上我想同时启动 2 个脚本并能够同时访问两个端口。如果我去终端并单独启动每个脚本,它会起作用,但我不想要那样。

脚本 1

#!/usr/bin/python
import sys
sys.path.append('/usr/local/lib/python2.7/dist-packages/')
import web
import time
urls = (
    '/', 'index'
)
class index:

    def GET(self):
        f = open('LiveFlow.txt', 'r')
        lineList = f.readlines()
        contents = lineList[-1]
        return contents

if __name__ == "__main__":
    app = web.application(urls, globals())
    app.run()

脚本 2

#!/usr/bin/python
import sys
sys.path.append('/usr/local/lib/python2.7/dist-packages/')
import web
import time

class MyApplication(web.application):
          def run(self, port=8080, *middleware):
              func = self.wsgifunc(*middleware)
              return web.httpserver.runsimple(func, ('0.0.0.0', port))

urls = (

    '/', 'index'

)

class index:


    def GET(self):

        f2 = open('FlowMeterOutput.txt', 'r')
        lineList1 = f2.readlines()
        contents1 = lineList1[-1]

        return contents1

if __name__ == "__main__":

    app = web.application(urls, globals())
    web.httpserver.runsimple(app.wsgifunc(), ("0.0.0.0", 8888))

标签: pythonraspberry-piweb.py

解决方案


您应该能够通过在自己的线程中运行它们来做到这一点,如下所示:

import threading

# ... two servers ...

def server1():
    app = web.application(urls, globals())
    app.run()

def server2():
    app = web.application(urls, globals())
    web.httpserver.runsimple(app.wsgifunc(), ("0.0.0.0", 8888))

if __name__ == "__main__":
    t1 = threading.Thread(target=server1)
    t2 = threading.Thread(target=server2)

    t1.start()
    t2.start()
    t1.join()
    t2.join()

此外,您似乎正在使用目前非常旧的 python 2.7。除非有某些特定原因,否则您应该使用 Python 3。如果不是全部,您的大多数代码都应该在 Python 3 中正常工作。


推荐阅读