我正在Windows上编写一个简单的python网络服务器.
它可以工作,但现在我想运行动态脚本(php或py),而不仅是html页面.
这是我的代码:
from BaseHTTPServer import HTTPServer
from CGIHTTPServer import CGIHTTPRequestHandler
class RequestsHandler(CGIHTTPRequestHandler):
cgi_directories = ["/www"] #to run all scripts in '/www' folder
def do_GET(self):
try:
f = open(curdir + sep + '/www' + self.path)
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
self.wfile.write(f.read())
f.close()
except IOError:
self.send_error(404, "Page '%s' not found" % self.path)
def main():
try:
server = HTTPServer(('', 80), RequestsHandler)
server.serve_forever()
except KeyboardInterrupt:
server.socket.close()
if __name__ == '__main__':
main()
如果我将php代码放在www文件夹中,则会显示页面,但代码不会被解释
我该怎么办?谢谢
解决方法:
我认为您正在研究工程.
#!/usr/bin/env python
import CGIHTTPServer
def main():
server_address = ('', 8000)
handler = CGIHTTPServer.CGIHTTPRequestHandler
handler.cgi_directories = ['/cgi']
server = CGIHTTPServer.BaseHTTPServer.HTTPServer(server_address, handler)
try:
server.serve_forever()
except KeyboardInterrupt:
server.socket.close()
if __name__ == '__main__':
main()