Question

I am quite new to the python local server. I have found some script which help me set up the local server through the python program. Below is my modified code and I am calling this from other code:

import sys
from SimpleHTTPServer import SimpleHTTPRequestHandler
import BaseHTTPServer
import webbrowser
def setup():
    HandlerClass = SimpleHTTPRequestHandler
    ServerClass  = BaseHTTPServer.HTTPServer
    Protocol = "HTTP/1.0"

    port = 8888 
    server_address = ('127.0.0.1', port)

    HandlerClass.protocol_version = Protocol
    httpd = ServerClass(server_address, HandlerClass)

    sa = httpd.socket.getsockname()
    print "Serving HTTP on", sa[0], "port", sa[1], "..."

    new = 2
    url = "127.0.0.1:8888/webVisual/tree_structure.html"
    webbrowser.open(url,new=new)

    httpd.serve_forever()

There are two questions regarding to this code:

  1. I try to browse one local html file on the real browser, I noticed that I can only put this piece of code before serve_forever(). Is this the right way to do?

  2. When I try to close the browser, I noticed that this program keeps running, I am thinking that this may be caused by the serve_forever() function. Is that right? And how can I end the server after I close the browser?

Was it helpful?

Solution

  1. if you write webbrowser.open after httpd.serve_forever, httpd.serve probably blocks the execution and webbrowser.open is never executed. That's why you are not seeing browser. You can put a print after httpd as experiment, it should never print.

  2. webbrowser.open starts a browser in a process that is different from httpd.

So when you close webbrowser, nothing will happen to httpd.serve_forever(). Like the name suggests, httpd.serve_forever() will serve the http server forever until you manually kill it by ctrl+c or some script like kill -9 .

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top