[英]Start simple web server and launch browser simultaneously in Python
I want to start a simple web server locally, then launch a browser with an url just served. 我想在本地启动一个简单的Web服务器,然后启动一个带有刚刚提供的url的浏览器。 This is something that I'd like to write,
这是我想写的东西,
from wsgiref.simple_server import make_server
import webbrowser
srv = make_server(...)
srv.blocking = False
srv.serve_forever()
webbrowser.open_new_tab(...)
try:
srv.blocking = True
except KeyboardInterrupt:
pass
print 'Bye'
The problem is, I couldn't find a way to set a blocking
option for the wsgiref simple server. 问题是,我找不到为wsgiref简单服务器设置
blocking
选项的方法。 By default, it's blocking, so the browser would be launched only after I stopped it. 默认情况下,它处于阻止状态,因此只有在我停止浏览器后才能启动浏览器。 If I launch the browser first, the request is not handled yet.
如果我先启动浏览器,则该请求尚未处理。 I'd prefer to use a http server from the standard library, not an external one, like tornado.
我更喜欢使用标准库中的http服务器,而不是像龙卷风那样使用外部服务器。
You either have to spawn a thread with the server, so you can continue with your control flow, or you have to use 2 python processes. 您要么必须在服务器上产生一个线程,然后才能继续控制流,要么必须使用2个python进程。
untested code, you should get the idea 未经测试的代码,你应该明白
class ServerThread(threading.Thread):
def __init__(self, port):
threading.Thread.__init__(self)
def run(self):
srv = make_server(...)
srv.serve_forever()
if '__main__'==__name__:
ServerThread().start()
webbrowser.open_new_tab(...)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.