0

Is there a way that I can preview my html file using python? My html file basically is a bar chart that I want the user to see once he or she runs a python file.

petezurich
  • 9,280
  • 9
  • 43
  • 57

3 Answers3

0

You can use either Flask or Django python web framework whichs are pure in python. I am currently using with Django and it even comes with developer server and template tags which makes life super easy.

Django tutorial

Rarblack
  • 4,559
  • 4
  • 22
  • 33
  • How do I do that? I tried using a web framework like Flask, but I keep getting a blank page. Here is a post that I made from about Flask. https://stackoverflow.com/questions/53439936/trouble-with-hosting-template-files-using-flask –  Nov 23 '18 at 20:05
  • I am not alot familiar with flask but I can guide you in django – Rarblack Nov 23 '18 at 20:08
  • Ok, I will take whatever help I can get. –  Nov 23 '18 at 20:27
  • I would suggest you to install django in virtual environment but you can also install it directly to your system – Rarblack Nov 23 '18 at 20:54
0

The user can run the python commands which generate a local html file, then open it with a local browser

import webbrowser, os

# first you save html content to a file
filename = 'yourpage.html'
html_content = "<html><head>This is header</head><body>This is body</body></html>"
f = open(filename,"w")
f.write(html_content)
f.close()

# then you use it with local browser
webbrowser.open('file://' + os.path.realpath(filename))

Tested on Ubuntu using python 3.6 and 2.7

Theo
  • 1
  • 2
  • if it is a `bar char`the mathplotlib could aso do the trick without the HTML – LoneWanderer Nov 23 '18 at 20:29
  • I am not sure this will work for him because he could have himself opened html in the browser without any need of python. I thin he wants to do something more complicated later. – Rarblack Nov 23 '18 at 20:34
0

Here's something similar to @Theo's answer, except it uses a named temporary file and spawns the [default] browser as a separate process.

import subprocess
import sys
from tempfile import NamedTemporaryFile

html = '''
    <!DOCTYPE html>
    <html>
      <head>
        <title>Chart Preview</title>
      </head>
      <body>
        <p>Here's your bar chart:</p>
          <!-- html for your bar chart goes here -->
      </body>
    </html>
'''

with NamedTemporaryFile(mode='wt', suffix='.html', delete=False) as temp_file:
    temp_file.write(html)
    temp_filename = temp_file.name  # Save temp file's name.

command = '"%s" -m webbrowser -n "file://%s"' % (sys.executable, temp_filename)
browser = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

print('back in the main script...')
martineau
  • 119,623
  • 25
  • 170
  • 301