It is often nice to display something in a web browser, perhaps as an easy way to display rich output or for testing purposes. Sometimes the baggage of a temporary file is not desired when doing this.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
import BaseHTTPServer import webbrowser def LoadInDefaultBrowser(html): """Display html in the default web browser without creating a temp file. Instantiates a trivial http server and calls webbrowser.open with a URL to retrieve html from that server. """ class RequestHandler(BaseHTTPServer.BaseHTTPRequestHandler): def do_GET(self): bufferSize = 1024*1024 for i in xrange(0, len(html), bufferSize): self.wfile.write(html[i:i+bufferSize]) server = BaseHTTPServer.HTTPServer(('127.0.0.1', 0), RequestHandler) webbrowser.open('http://127.0.0.1:%s' % server.server_port) server.handle_request() if __name__ == '__main__': LoadInDefaultBrowser('<b>Hello World</b>')
This creates an http server that handles exactly 1 request and then terminates. A web browser is then launched to retrieve the document from that http server. The function waits for the http server to finish processing the request and terminate before returning.
Update #1: Changed to use webbrowser.open instead of os.startfile so that it will work on platforms other than Windows.
Update #2: The http server was being created in a background thread. That isn't necessary as long as the server is created before opening the web browser and the request is handled after opening the web browser.