首页 > 解决方案 > CGI - HTML 到 python

问题描述

当我尝试执行程序时,我正在关注教程CGI

#!C:/Python27/python.exe
# Import modules for CGI handling 
import cgi, cgitb 

# Create instance of FieldStorage 
form = cgi.FieldStorage() 

# Get data from fields
first_name = form.getvalue('first_name')
last_name  = form.getvalue('last_name')

print "Content-type:text/html\r\n\r\n"
print "<html>"
print "<head>"
print "<title>Hello - Second CGI Program</title>"
print "</head>"
print "<body>"
print "<h2>Hello %s %s</h2>" % (first_name, last_name)
print "</body>"
print "</html>"

HTML 文件

<form action = "/cgi-bin/hello_get.py" method = "get">
First Name: <input type = "text" name = "first_name">  <br />

Last Name: <input type = "text" name = "last_name" />
<input type = "submit" value = "Submit" />
</form>

在我提交值的浏览器中,我的 python 文件按原样显示。浏览器显示了我的代码。即使它没有得到名字和姓氏。问题是什么?

我无法找到我在哪里做错了。

标签: pythonpython-2.7cgi

解决方案


如果我理解正确,您是说 Web 服务器正在显示您的 Python 程序的源代码,而不是执行源代码。根据您的 shebang 规范,您似乎在 Windows 下运行。根据您使用的 Web 服务器,例如 IIS 或 Apache,您需要配置 Web 服务器,以便它知道具有 .py 扩展名的文件将由 Python 解释器执行,因为它显然忽略了 shebang 规范。例如,如果使用 Apache,您的 httpd 配置文件可能包含以下行:

AddHandler cgi-script .py
ScriptInterpreterSource Registry-Strict

在第二行中,Web 服务器将忽略 shebang 并使用与文件类型 .py 关联的任何程序,这应该是您的 Python 解释器。这可能是您想要的,因为您可能正在升级您的解释器并改变它的位置。在这种情况下,您可能应该将 shebang 编码为:

#!/usr/bin/env python

推荐阅读