0

我在下面有这个 python 代码,它适用于从与脚本相同的目录传递的简单 html 页面。什么不起作用是我想从 cgi-bin 目录运行一个 cgi 脚本。这个想法是拥有可移植的 python,运行一个脚本,启动 Web 服务器并使用 ajax、SQLite 等提供 cgi 页面。

# helper to load url
# runs webserver and loads url with webbrowswer module
import sys

def load_url(path):
    PORT = 80
    httpd = StoppableHTTPServer(("127.0.0.1",PORT), handler)
    thread.start_new_thread(httpd.serve, ())
    webbrowser.open_new('http://localhost:%s/%s'%(PORT,path))
    input("Press <RETURN> to stop server\n")
    httpd.stop()
    print("To restart server run: \n%s"%server)


if sys.version_info[0] == 2:
    import BaseHTTPServer, CGIHTTPServer
    import cgitb; cgitb.enable()  ## This line enables CGI error reporting
    import socket
    import thread
    import webbrowser
    #handler = SimpleHTTPServer.SimpleHTTPRequestHandler
    handler = CGIHTTPServer.CGIHTTPRequestHandler
    input = raw_input
    server = "python -m SimpleHTTPServer 80"

    class StoppableHTTPServer(BaseHTTPServer.HTTPServer):

        def server_bind(self):
            BaseHTTPServer.HTTPServer.server_bind(self)
            self.socket.settimeout(1)
            self.run = True

        def get_request(self):
            while self.run:
                try:
                    sock, addr = self.socket.accept()
                    sock.settimeout(None)
                    return (sock, addr)
                except socket.timeout:
                    pass

        def stop(self):
            self.run = False

        def serve(self):
            while self.run:
                self.handle_request()


else:
    import http.server, http.server
    import socket
    import _thread as thread
    import webbrowser
    #handler = http.server.SimpleHTTPRequestHandler
    handler = http.server.CGIHTTPRequestHandler
    server = "python -m http.server 80"

    class StoppableHTTPServer(http.server.HTTPServer):

        def server_bind(self):
            http.server.HTTPServer.server_bind(self)
            self.socket.settimeout(1)
            self.run = True

        def get_request(self):
            while self.run:
                try:
                    sock, addr = self.socket.accept()
                    sock.settimeout(None)
                    return (sock, addr)
                except socket.timeout:
                    pass

        def stop(self):
            self.run = False

        def serve(self):
            while self.run:
                self.handle_request()

load_url("cgi-bin/page01.py")
4

0 回答 0