【问题标题】:Running 2 web.py servers from the same script Python从同一个脚本 Python 运行 2 个 web.py 服务器
【发布时间】:2020-09-26 19:38:38
【问题描述】:

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

【问题讨论】:

    标签: python raspberry-pi web.py


    【解决方案1】:

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

    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 中正常工作。

    【讨论】:

    • 感谢@gerwin 的协助。我得到了一些不受欢迎的结果,太多了,无法在这里发布。但我目前正在更新我的 Raspian OS 和我的 Python 版本。很快我会有更好的答案
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-03
    • 1970-01-01
    • 1970-01-01
    • 2014-03-15
    • 1970-01-01
    • 2017-03-30
    相关资源
    最近更新 更多