Search code examples
pythonpython-multithreadinghttp.server

Unable to run python http server in background with threading


I'm trying to run a python http server in the background using threading. I came across several references that do the following:

import threading
import http.server
import socket 
from http.server import HTTPServer, SimpleHTTPRequestHandler

debug = True
server = http.server.ThreadingHTTPServer((socket.gethostname(), 6666), SimpleHTTPRequestHandler)
if debug:
    print("Starting Server in background")
    thread = threading.Thread(target = server.serve_forever)
    thread.daemon = True
    thread.start()
else:
    print("Starting Server")
    print('Starting server at http://{}:{}'.format(socket.gethostname(), 6666))
    server.serve_forever()

When thread.daemon is set to True, the program will finish without starting the server (nothing running on port 6666). And when I set thread.daemon to False, it starts the server in foreground and blocks the terminal until I kill it manually.

Any idea on how to make this work?


Solution

  • In both cases the server is launched in the background, in the separate thread. This means that thread.start() launches the server and python continues executing the rest of the code in the main thread.

    However, there seems to be nothing else to execute in your program. Python reaches the end of the file and the main thread is done.

    The OS requires all non-daemon threads to be done before the process could be finished. When thread.daemon is set to False the OS waits until the server thread exits (which will never happen, as the name serve_forever implies). When it is True the process is closed immediately after the main thread is done.

    Put whatever code you want to be executed asynchronously after the thread.start() and you're done!