我正在尝试这个:
import multiprocessing
from wsgiref.simple_server import make_server
import webbrowser
import time
def application(environ, start_response):
start_response("200 OK", [("Content-Type", "text/plain")])
return ["Hello!"]
class Server(multiprocessing.Process):
def run(self):
print "HTTP Server starts."
server = make_server(host = "127.0.0.1",
port = 88,
app = application)
try:
server.serve_forever()
except (KeyboardInterrupt, SystemExit):
print "HTTP Server stopped."
raise
httpd = Server()
httpd.start()
#webbrowser.open("http://127.0.0.1:88")
time.sleep(3)
httpd.terminate()
httpd.join()
print "End"
如果我取消注释 webbrowser 行,浏览器将不会停止打开新窗口。为什么?
我还是不太了解多处理模块,但像这样的东西应该很简单。这是怎么做到的?
编辑:
第一个注释在 http://docs.python.org/2/library/multiprocessing.html “要求 main 模块可以被 child 导入”,所以:
if __name__=='__main__':
httpd = Server()
httpd.start()
webbrowser.open("http://127.0.0.1:88")
time.sleep(3)
httpd.terminate()
httpd.join()
print "End"
似乎工作正常。
但我想知道如何向服务器发送 SystemExit 信号。更好的方法?
最佳答案
Windows 无法通过 fork 现有进程来创建子进程,这在 Unices 上是可能的。在 Windows 上还有一些额外的事情需要考虑:http://docs.python.org/2/library/multiprocessing#windows
因此在 Windows 中创建了一个新进程并导入了代码。任何无条件运行的代码都会在子进程中执行。在您的情况下,创建一个新的服务器进程和一个浏览器窗口。这将导入您的主模块...
正如您发现的那样,解决方案是使用 if __name__ == '__main__':
习惯用法。
关于python - 如何启动 http 服务器,然后打开 Web 浏览器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16866091/