views:

40

answers:

1

I want to start a simple web server locally, then launch a browser with an url just served. This is something that I'd like to write,

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'

The problem is, I couldn't find a way to set a blocking option for the wsgiref simple server. By default, it's blocking, so the browser would be launched only after I stopped it. If I launch the browser first, the request is not handled yet. I'd prefer to use a http server from the standard library, not an external one, like tornado.

+1  A: 

You either have to spawn a thread with the server, so you can continue with your control flow, or you have to use 2 python processes.

untested code, you should get the idea


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(...)
knitti