问题
I am following the tutorial CGI, when I try to execute the program
#!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>"
The HTML file
<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>
In my browser on submitting the values, my python file is displaying as it is. Blankly my code was shown by the browser. Even it didn't get the first name and last name. What is the problem?
I am unable to find where I am doing the mistake.
回答1:
If I understand correctly, you are saying that the web server is displaying the source of your Python program instead of executing the source. Based on your shebang specification, it appears you are running under Windows. Depending on what web server you are using, IIS or Apache for example, you need to configure the web server so that it knows that files with .py extensions are to be executed by the Python interpreter for it is clearly ignoring the shebang specification. For example, if using Apache your httpd configuration file might contain the following lines:
AddHandler cgi-script .py
ScriptInterpreterSource Registry-Strict
With the second line, the web server will ignore the shebang and use whatever program is associated with the filetype .py, which should be your Python interpreter. This is probably what you want as you may be upgrading your interpreter and its location changing. In this case you should probably code the shebang as:
#!/usr/bin/env python
来源:https://stackoverflow.com/questions/53912765/cgi-html-to-python