I have a script that sends a request to an HTTP server.

HTTP server script (snippet):

...

class MyHandler(BaseHTTPServer.BaseHTTPRequestHandler):
  def do_GET(sa):
    pdict = cgi.parse_header(sa.headers.getheader('referer'))
    q = pdict[0]
    q = urllib.unquote(q)

    if q == "enternetixplorer" # basically just ignore this, doesn't have to do with the question
      sa.wfile.write("blah blah blah")
      # now restart server
      httpd.server_close()
      python = sys.executable
      os.execl(python, python, * sys.argv)

...

The "blah blah blah" is sent back, but the connection does not seem to close, and my script is waiting forever until I abort the server. (My thought is BaseHTTPServer automatically closes connection when the last part in "do_GET()" is computed, but I prevent this by restarting the script.)

If I'm right, how do I close the connection? If not, what else might be the problem?

Edit: The server script HAS to restart the entire program.

有帮助吗?

解决方案

When you execute:

os.execl(python, python, * sys.argv)

The Python documentation for os.exec* says this:

These functions all execute a new program, replacing the current process; they do not return. On Unix, the new executable is loaded into the current process, and will have the same process id as the caller. Errors will be reported as OSError exceptions.

So, when you call that function, the do_GET function hangs and never returns, so the HTTP server never flushes the end of the HTTP message.

I think in your case, the easiest change is to call os.fork before calling exec, then call exec only in the child process. Let the parent process return from the do_GET function.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top