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.
webbrowser? <p>Sorry if this is a silly question, but wouldn’t it be better to use the webbrowser module?
Works great with difflib.HtmlDiff. Tried this recipe today during debugging, using it to display the HTML output of difflib.HtmlDiff. If you haven't used this new feature of difflib, this recipe makes it very easy to use the webbrowser to show a graphical representation of the differences between two text files.
webbrowser. Ah, I hadn't realized that os.startfile was Windows only. Replacing os.startfile with webbrowser.open should provide equivalent functionality on Windows and make the recipe work on other platforms as well. I don't believe there is anything Windows specific about the technique used for serving up the data. I undertand that the specification of port 0 in order to dynamically find an available port might not work on some platforms.