【发布时间】:2018-11-23 19:57:26
【问题描述】:
有没有办法可以使用 python 预览我的 html 文件?我的 html 文件基本上是一个条形图,我希望用户在他或她运行 python 文件时看到它。
【问题讨论】:
标签: javascript python html
有没有办法可以使用 python 预览我的 html 文件?我的 html 文件基本上是一个条形图,我希望用户在他或她运行 python 文件时看到它。
【问题讨论】:
标签: javascript python html
您可以使用Flask 或Django 纯python 中的python 网络框架。我目前正在使用 Django,它甚至带有开发人员服务器和模板标签,这让生活变得超级简单。
姜戈tutorial
【讨论】:
用户可以运行python命令生成本地html文件,然后用本地浏览器打开
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))
使用 python 3.6 和 2.7 在 Ubuntu 上测试
【讨论】:
bar charmathplotlib 也可以在没有 HTML 的情况下完成这项工作
这与@Theo 的answer 类似,不同之处在于它使用命名的临时文件并将[默认] 浏览器作为单独的进程生成。
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...')
【讨论】: