【问题标题】:How do I start a http server and then open a web browser?如何启动 http 服务器然后打开 Web 浏览器?
【发布时间】:2013-05-27 19:04:32
【问题描述】:

我正在尝试这个:

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 的第一条注释“要求 ma​​in 模块可由子模块导入”,因此:

    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 信号。更好的方法?

【问题讨论】:

  • 你是如何开始这个程序的?即“python file.py”?
  • 我正在使用 IDLE 进行测试
  • 我现在要测试,但看起来它可以正常工作(并且符合预期)
  • 是的,从命令行在 OSX 上对我来说工作正常。
  • 你是否偶然在 Windows 上运行?

标签: python windows python-2.7 multiprocessing


【解决方案1】:

Windows 不能分叉现有进程来创建子进程,就像在 Unices 上一样。在 Windows 上还有一些额外的事情需要考虑:http://docs.python.org/2/library/multiprocessing#windows

因此在 Windows 中创建了一个新进程并导入了代码。任何无条件运行的代码都将在子进程中执行。在您的情况下,创建一个新的服务器进程和一个浏览器窗口。这将导入您的主模块...

如您所见,解决方案是使用if __name__ == '__main__': 成语。

【讨论】:

    猜你喜欢
    • 2018-12-20
    • 2012-03-10
    • 1970-01-01
    • 2015-12-20
    • 2017-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多