在Python中同时启动简单Web服务器和浏览器
我想在本地启动一个简单的网页服务器,然后用浏览器打开刚刚提供的链接。这是我想写的内容:
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'
问题是,我找不到设置wsgiref简单服务器的blocking
选项的方法。默认情况下,它是阻塞的,所以只有在我停止服务器后,浏览器才会启动。如果我先启动浏览器,请求还没有被处理。我更希望使用标准库中的http服务器,而不是像tornado这样的外部服务器。
1 个回答
1
你要么需要在服务器上创建一个线程,这样你就可以继续进行你的操作,要么就得使用两个Python进程。
这段代码没有经过测试,但你应该能明白意思。
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(...)