1

私はこれを試しています:

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 行のコメントを外すと、ブラウザは新しいウィンドウを開くのをやめません。なんで?

multiprocessing モジュールについてはまだよくわかりませんが、このようなものは簡単なはずです。これはどのように行われますか?

編集:

http://docs.python.org/2/library/multiprocessing.htmlの最初の注記では、「メインモジュールが子によってインポート可能である必要がある」ため、次のようになります。

    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 をサーバーに通知できるのでしょうか。より良い方法は?

4

1 に答える 1

3

Windows では、既存のプロセスを fork して子プロセスを作成することはできません。これは Unice で可能です。Windows で考慮すべき点がいくつかあります: http://docs.python.org/2/library/multiprocessing#windows

そのため、Windows では新しいプロセスが作成され、コードがインポートされます。無条件に実行されるコードは、子プロセスで実行されます。あなたの場合、新しいサーバープロセスとブラウザウィンドウを作成します。メインモジュールをインポートするもの...

if __name__ == '__main__':あなたが発見したように、解決策はイディオムを使用することです。

于 2013-05-31T22:02:02.313 に答える