Display html in a web browser without creating a temp file. Instantiates a trivial http server and uses the webbrowser module to open a URL to retrieve html from that server. Parameters ---------- html: str HTML string to display using, new, autoraise:
(html, using=None, new=0, autoraise=True)
| 611 | |
| 612 | |
| 613 | def open_html_in_browser(html, using=None, new=0, autoraise=True): |
| 614 | """ |
| 615 | Display html in a web browser without creating a temp file. |
| 616 | |
| 617 | Instantiates a trivial http server and uses the webbrowser module to |
| 618 | open a URL to retrieve html from that server. |
| 619 | |
| 620 | Parameters |
| 621 | ---------- |
| 622 | html: str |
| 623 | HTML string to display |
| 624 | using, new, autoraise: |
| 625 | See docstrings in webbrowser.get and webbrowser.open |
| 626 | """ |
| 627 | if isinstance(html, str): |
| 628 | html = html.encode("utf8") |
| 629 | |
| 630 | browser = None |
| 631 | |
| 632 | if using is None: |
| 633 | browser = webbrowser.get(None) |
| 634 | else: |
| 635 | if not isinstance(using, tuple): |
| 636 | using = (using,) |
| 637 | for browser_key in using: |
| 638 | try: |
| 639 | browser = webbrowser.get(browser_key) |
| 640 | if browser is not None: |
| 641 | break |
| 642 | except webbrowser.Error: |
| 643 | pass |
| 644 | |
| 645 | if browser is None: |
| 646 | raise ValueError("Can't locate a browser with key in " + str(using)) |
| 647 | |
| 648 | class OneShotRequestHandler(BaseHTTPRequestHandler): |
| 649 | def do_GET(self): |
| 650 | self.send_response(200) |
| 651 | self.send_header("Content-type", "text/html") |
| 652 | self.end_headers() |
| 653 | |
| 654 | bufferSize = 1024 * 1024 |
| 655 | for i in range(0, len(html), bufferSize): |
| 656 | self.wfile.write(html[i : i + bufferSize]) |
| 657 | |
| 658 | def log_message(self, format, *args): |
| 659 | # Silence stderr logging |
| 660 | pass |
| 661 | |
| 662 | server = HTTPServer(("127.0.0.1", 0), OneShotRequestHandler) |
| 663 | browser.open( |
| 664 | "http://127.0.0.1:%s" % server.server_port, new=new, autoraise=autoraise |
| 665 | ) |
| 666 | |
| 667 | server.handle_request() |
| 668 | |
| 669 | |
| 670 | class BrowserRenderer(ExternalRenderer): |