我正在本地使用我的 mac 上的 python 脚本使用
python3 -m http.server --cgi
我的脚本有效。我创建了一个图形和一个动态网页,并在新选项卡中打开该网页。我不喜欢的是它在脚本地址所在的位置留下一个空白窗口。因此,当我使用表单运行网页并点击提交时。我得到一个空白页和一个新页面。我只是希望它转到新页面。我是 python 的新手,所以我不太确定我做错了什么。这是我的脚本:
#!/usr/bin/env python3
import pyromat as pm
import matplotlib.pyplot as plt
import numpy as np
import webbrowser
# Create a temperature array in steps of 10K
T = np.arange(300,2000,10)
# Get the Oxygen object
O2 = pm.get('ig.O2')
f = plt.figure(1) # Call up figure 1
f.clf() # clear it (if it already exists)
ax = f.add_subplot(111) # Create an axes object on the figure
ax.plot(T, O2.cp(T)) # Add a curve to that axes
ax.set_xlabel('Temperature (K)')
ax.set_ylabel('Specific Heat (kJ/kg/K)')
f.savefig('cp.png') # Make a file
f = open('test.html','w')
message = """<html>
<head></head>
<body><p>Graph Test</p><img src="cp.png"></body>
</html>"""
f.write(message)
f.close()
filename = 'file:///Users/pzb4/Documents/Environments/test.html'
webbrowser.open(filename,new=0,autoraise=True)
我的想法是创建一个表单,我可以在其中更改图形的输入。理想情况下,它只会重写表单页面,以便学生可以不断更改数据并查看它如何影响图表。
请您参考如下方法:
由于您将其作为 CGI 脚本运行,因此您可以写入标准输出:
#!/usr/bin/env python3
import pyromat as pm
import matplotlib.pyplot as plt
import numpy as np
import webbrowser
from io import BytesIO
import base64
# Create a temperature array in steps of 10K
T = np.arange(300,2000,10)
# Get the Oxygen object
O2 = pm.get('ig.O2')
f = plt.figure(1) # Call up figure 1
f.clf() # clear it (if it already exists)
ax = f.add_subplot(111) # Create an axes object on the figure
ax.plot(T, O2.cp(T)) # Add a curve to that axes
ax.set_xlabel('Temperature (K)')
ax.set_ylabel('Specific Heat (kJ/kg/K)')
image_bytes = BytesIO()
f.savefig(image_bytes, format="png") # write bytes to in-memory object
image_bytes.seek(0) # go to beginning of bytes
# print HTTP headers
print("Content-Type: text/html; charset=utf-8")
print()
# encode as Base64
src = base64.b64encode(image_bytes.read())
message = """<html lang="en"><head><title>Result</title></head>
<body><p>Graph Test</p><img src="data:image/png;base64,{}"></body></html>"""
# print HTML with embedded image
print(message.format(src))
这避免了将 HTML 或图像写入磁盘。相反,它将 HTML 写入标准输出(应该显示在浏览器中)并将图像作为 Base64 数据直接嵌入到 HTML 源中。
