Starting simple python web server in background and continue script execution
Asked Answered
U

2

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?

Unsuccessful answered 2/8, 2018 at 17:29 Comment(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.Labourite
If the thread never finishes its task, it shouldn't progress beyond the line where it starts.Participle
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.Blazer
L
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().

Labourite answered 2/8, 2018 at 17:47 Comment(0)
P
2

For Python 3 you can use this:

import threading

threading.Thread(target=create_server).start()
Pilloff answered 18/4, 2020 at 18:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.