Displaying a temporary html file with webbrowser in Python

4.7k views Asked by At

Really simple, I want to create a temporary html page that I display with the usual webbrowser.

Why does the following code produce an empty page?

import tempfile 
import webbrowser 
import time

with tempfile.NamedTemporaryFile('r+', suffix = '.html') as f:
    f.write('<html><body><h1>Test</h1></body></html>') 
    webbrowser.open('file://' + f.name) 
    time.sleep(1) # to prevent the file from dying before displayed
4

There are 4 answers

3
Alex Ivanov On

This piece of code is an edition to the previews one and continuation of the discussion with the OP. It shows time.sleep() after webbrowser.open(). I don't think it's actually needed because the /tmp directory is emptied automatically on a regular bases by the OS but the OP commented that if he deletes the temp file via Python it is deleted before it gets fully loaded by the browser. Most likely it happens because the "browser" process is detached from this scrip which is its parent and Python doesn't wait for the process completion before executing the next statement. I though it would be clear for everyone without explanation but obviously you, guys, don't read comments.

import os, time

#      ...

webbrowser.open('file://' + path)
time.sleep(1)

if os.path.exists(path):
    os.remove(path)
2
Alex Ivanov On

Because your file doesn't exist on the disk and sits entirely in memory. That's why the browser starts but opens nothing since no code has been provided.

Try this:

#!/usr/bin/python

import tempfile 
import webbrowser 

tmp=tempfile.NamedTemporaryFile(delete=False)
path=tmp.name+'.html'

f=open(path, 'w')
f.write("<html><body><h1>Test</h1></body></html>")
f.close()
webbrowser.open('file://' + path)
1
Oscar Giles On

Just change the file's current position.

import tempfile 
import webbrowser 
import time

with tempfile.NamedTemporaryFile('r+', suffix = '.html') as f:
    f.write('<html><body><h1>Test</h1></body></html>') 
    webbrowser.open('file://' + f.name) 
    f.seek(0)
    time.sleep(1) # to prevent the file from dying before displayed
1
PADYMKO On

Tested on Python 3.4.

import subprocess
import webbrowser
from http.server import BaseHTTPRequestHandler, HTTPServer


PORT = 7000
HOST = '127.0.0.1'
SERVER_ADDRESS = '{host}:{port}'.format(host=HOST, port=PORT)
FULL_SERVER_ADDRESS = 'http://' + SERVER_ADDRESS


def TemproraryHttpServer(page_content_type, raw_data):
    """
    A simpe, temprorary http web server on the pure Python 3.
    It has features for processing pages with a XML or HTML content.
    """

    class HTTPServerRequestHandler(BaseHTTPRequestHandler):
        """
        An handler of request for the server, hosting XML-pages.
        """

        def do_GET(self):
            """Handle GET requests"""

            # response from page
            self.send_response(200)

            # set up headers for pages
            content_type = 'text/{0}'.format(page_content_type)
            self.send_header('Content-type', content_type)
            self.end_headers()

            # writing data on a page
            self.wfile.write(bytes(raw_data, encoding='utf'))

            return

    if page_content_type not in ['html', 'xml']:
        raise ValueError('This server can serve only HTML or XML pages.')

    page_content_type = page_content_type

    # kill a process, hosted on a localhost:PORT
    subprocess.call(['fuser', '-k', '{0}/tcp'.format(PORT)])

    # Started creating a temprorary http server.
    httpd = HTTPServer((HOST, PORT), HTTPServerRequestHandler)

    # run a temprorary http server
    httpd.serve_forever()


if __name__ == '__main__':

    def run_xml_server():

        xml_data = """
        <note>
        <to>Tove</to>
        <from>Jani</from>
        <heading>Reminder</heading>
        <body>Don't forget me this weekend!</body>
        </note>
        """

        # open in a browser URL and see a result
        webbrowser.open(FULL_SERVER_ADDRESS)

        # run server
        TemproraryHttpServer('xml', xml_data)

    def run_html_server():

        html_data = """
        <!DOCTYPE html>
        <html>
        <head>
        <title>Page Title</title>
        </head>
        <body>
        <h1>This is a Heading</h1>
        <p>This is a paragraph.</p>
        </body>
        </html>
        """

        # open in a browser URL and see a result
        webbrowser.open(FULL_SERVER_ADDRESS)

        # run server
        TemproraryHttpServer('html', html_data)

    # choice needed server:

    # run_xml_server()
    # run_html_server()