1

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?

Daniel Walker
  • 6,380
  • 5
  • 22
  • 45
Elie
  • 337
  • 3
  • 6
  • 14

1 Answers1

5

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!

Andrew Morozko
  • 2,576
  • 16
  • 16
  • Thanks for the explanation! So in case i want this to be run in bckground, i have to do it from bash and run the script using "nohup &" right? I thought python offers this functionality. – Elie Sep 17 '20 at 05:30
  • 1
    @Elie yep. In fact you are looking at pretty much the same problem, only with child processes, not threads. Python is a child process of bash, so you must control how it behaves via bash. `&` is to not wait for process to end before returning to bash and `nohup` is to shield the python from receiving HUP signal if the parent bash is terminated, typically on disconnect from ssh. – Andrew Morozko Sep 17 '20 at 10:08