5

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?

Kevin
  • 2,852
  • 6
  • 21
  • 33
  • 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. – Andrej Kesely Aug 02 '18 at 17:33
  • If the thread never finishes its task, it shouldn't progress beyond the line where it starts. – Gigaflop Aug 02 '18 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`](https://docs.python.org/3/library/threading.html) module for a far more comfortable higher level interface for threads. – zwer Aug 02 '18 at 17:40

2 Answers2

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

Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91
2

For Python 3 you can use this:

import threading

threading.Thread(target=create_server).start()
feeeper
  • 2,865
  • 4
  • 28
  • 42