繁体   English   中英

有没有一种方法可以预览我的HTML文件?

[英]Is there a way that I can preview my html file?

有没有一种方法可以使用python预览html文件? 我的html文件基本上是一个条形图,我希望用户在运行python文件时能够看到它。

您可以使用FlaskDjango python网络框架,它们纯在python中。 我目前正在使用Django,它甚至附带了开发人员服务器和模板标签,这使生活变得异常轻松。

Django 教程

用户可以运行生成本地html文件的python命令,然后使用本地浏览器将其打开

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))

在Ubuntu上使用python 3.6和2.7测试

这类似于@Theo的答案 ,除了它使用命名的临时文件并生成[default]浏览器作为单独的进程。

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...')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM