CGIHTTPRequestHandler run php or python script in python

柔情痞子 提交于 2019-12-21 05:46:32

问题


I'm writing a simple python web-server on windows..

it works but now I want to run dynamic scripts (php or py) and not only html pages..

here is my code:

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()

if I put php code in www folder I get the page but the code isn't interpreted

what I have to do? thanks


回答1:


I think you are over engineering.

#!/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()



回答2:


Did you make the php file executable?? chmod +x spam.php (for Linux, I have no Idea how to make files executable on windows)

You would need the PHP interpreter installed on your PC as well

source from a reply HERE

You should also consider using THIS as an indirect alternative.




回答3:


The problem is with the CGIHTTPServer Class. It doesn't set CGI env variables. This has been fixed here:
https://github.com/gabrielgrant/tonto/blob/master/tonto.py



来源:https://stackoverflow.com/questions/5333632/cgihttprequesthandler-run-php-or-python-script-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!