CGI脚本文件在浏览器中显示代码而不是运行

1 投票
1 回答
2866 浏览
提问于 2025-04-21 02:57

我的cgi脚本是:

#!/usr/bin/env python

import cgi

reshtml='''Content-Type:text/html\n
<HTML>
<HEAD>
<title>
Friends CGI demo(dynamic screen)
</title>
</HEAD>
<body>
<h3>Friends list for:<i>%s</i></h3>
Your name is: <b>%s</b>
You have<b>%s</b>friends.
</body>
</HTML>'''

form = cgi.FieldStorage()
who = form['person'].value
howmany = form['howmany'].value
print(reshtml % (who, who, howmany))

在这里,服务器把整个脚本当作文本返回,而不是执行它。按照我的理解,它应该只返回reshtml的值,这样浏览器才能理解。我正在使用Python的网络服务器,并且在当前工作目录下成功执行了命令C:\Python32\Lib\http\server.py。那么这里到底出了什么问题呢?

1 个回答

0

这个模块默认的http服务器不支持CGI。如果你使用的是Python3.4,可能是因为你缺少了--cgi这个选项来启动http服务器:

c:\> python c:\python32\lib\http\server.py --cgi

或者,更方便的方法是:

c:\> python -mhttp.server --cgi

另一方面,如果你使用的是Python3.2,可以尝试下面的方法,这在两种环境下都能工作:

首先,创建一个名为httpd.py的文件:

import http.server

server_address = ('',8000)
server_class = http.server.HTTPServer
handler_class = http.server.CGIHTTPRequestHandler
httpd = server_class(server_address, handler_class)
httpd.serve_forever()

然后像这样运行它:

c:\> python \httpd.py

这样就可以正确地提供可执行的CGI文件,但前提是这些文件必须放在./cgi-bin/./htbin/目录下。

参考资料:

撰写回答