我正在使用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)
想法是创建一个表单,在其中可以更改图形的输入。理想情况下,它将只重写表单页面,以便学生可以不断更改数据并查看其如何影响图形。
答案 0 :(得分:1)
由于您将其作为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源中。