Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Displaying a temporary html file with webbrowser in Python

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
like image 516
PascalVKooten Avatar asked Jun 09 '15 14:06

PascalVKooten


People also ask

How do I open and read an HTML file in Python?

open() to open an HTML file within Python. Call codecs. open(filename, mode, encoding) with filename as the name of the HTML file, mode as "r" , and encoding as "utf-8" to open an HTML file in read-only mode.


1 Answers

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)
like image 106
Alex Ivanov Avatar answered Sep 28 '22 04:09

Alex Ivanov