3

I have the following code:

import SimpleHTTPServer
import SocketServer

def http_server():
    PORT = 80
    Handler = SimpleHTTPServer.SimpleHTTPRequestHandler
    httpd = SocketServer.TCPServer(("", PORT), Handler)
    httpd.serve_forever()

The problem with this is that, because of httpd.serve_forever(), it hangs the rest of the program. I'm assuming I could use threading to run this on its own thread, so the rest of the program can execute independently of the server, but I'm not sure how to implement this.

2
  • Your imports should be at module level, not inside of the function Commented Jul 18, 2013 at 0:51
  • @RyanHaining Yes, that's something I didn't catch when copy/pasting code around. Commented Jul 18, 2013 at 1:12

1 Answer 1

1

Simplest way, straight from the docs:

from threading import Thread

t = Thread(target=http_server)
t.start()

Note that this thread will be difficult to kill as-is, KeyboardInterrupts do not propagate to random threads that you've start()ed. You may want to set daemon=True or have some more sophisticated method to shut it down.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.