6

I am attempting to start a simple HTTP web server in python and then ping it with the selenium driver. I can get the web server to start but it "hangs" after the server starts even though I have started it in a new thread.

from socket import *
from selenium import webdriver
import SimpleHTTPServer
import SocketServer
import thread


def create_server():
    port = 8000
    handler = SimpleHTTPServer.SimpleHTTPRequestHandler
    httpd = SocketServer.TCPServer(("", port), handler)
    print("serving at port:" + str(port))
    httpd.serve_forever()


thread.start_new_thread(create_server())

print("Server has started. Continuing..")

browser = webdriver.Firefox()
browser.get("http://localhost:8000")

assert "<title>" in browser.page_source
thread.exit()

The server starts but the script execution stops after the server has started. The code after I start the thread is never executed.

How do I get the server to start and then have the code continue execution?

3
  • You are executing create_server() before you start_new_thread - which will execute serve_forever() and you are stuck. Put it inside lambda for example. Commented Aug 2, 2018 at 17:33
  • If the thread never finishes its task, it shouldn't progress beyond the line where it starts. Commented Aug 2, 2018 at 17:35
  • You should use thread.start_new_thread(create_server) (notice the missing brackets) because otherwise you'd be calling the function itself instead of having the threading code do that for you. Even better, use the threading module for a far more comfortable higher level interface for threads. Commented Aug 2, 2018 at 17:40

2 Answers 2

2

Start your thread with function create_server (without calling it ()):

thread.start_new_thread(create_server, tuple())

If you call create_server(), it will stop at httpd.serve_forever().

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

Comments

2

For Python 3 you can use this:

import threading

threading.Thread(target=create_server).start()

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.