python - 从同一个脚本 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))
解决方案
您应该能够通过在自己的线程中运行它们来做到这一点,如下所示:
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 中正常工作。
推荐阅读
- vba - 退出宏以在 powerpoint 中关闭 Chrome 或其他浏览器
- azure - 有没有办法使用 Powershell/Graph API 创建 Azure 密码保护
- javascript - 平台之间的浮点数是否一致?
- python - 更新语句中的 Python MySQL 动态变量
- c# - 键上的 MemoryCache 正则表达式
- php - 按关系列分组日期
- python - 将sqlalchemy输出转换为python中的列表字典
- c# - 如果“is”为假,如何输出变量?
- javascript - 离子输入禁用不透明度
- c# - Blazor WASM - Global Catch 401 并导航到所有 HttpClient 调用的登录页面