Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SimpleHTTPServer launched as a thread: does not daemonize

I would like to launch a SimpleHTTPServer in a separate thread, while doing something else (here, time.sleep(100)) in the main one. Here is a simplified sample of my code:

from SimpleHTTPServer import SimpleHTTPRequestHandler
from BaseHTTPServer import HTTPServer

server = HTTPServer(('', 8080), SimpleHTTPRequestHandler)
print 'OK UNTIL NOW'
thread = threading.Thread(target = server.serve_forever())
print 'STUCK HERE'
thread.setdaemon = True
try:
    thread.start()
except KeyboardInterrupt:
    server.shutdown()
    sys.exit(0)

print 'OK'

time.sleep(120)

However, the thread remains "blocking", i.e. is not launched as a daemon and the interpreter does not reach the print 'OK'. It does not neither reach the STUCK HERE.

I have though that the thread would only be initialized when calling threading.Thread(...) and that the main thread would still go further until it found the thread.start instruction to launch it.

Is there any better way to accomplish this task?

like image 211
philippe Avatar asked Feb 05 '15 16:02

philippe


People also ask

What does Python SimpleHTTPServer do?

The SimpleHTTPServer module is a Python module that enables a developer to lay the foundation for developing a web server. However, as sysadmins, we can use the module to serve files from a directory. The module loads and serves any files within the directory on port 8000 by default.

How do you close a simple HTTP server in Python?

To stop the server, I just press Ctrl+C.

How is Python thread implemented?

Use the Python threading module to create a multi-threaded application. Use the Thread(function, args) to create a new thread. Call the start() method of the Thread class to start the thread. Call the join() method of the Thread class to wait for the thread to complete in the main thread.


1 Answers

Change this:

thread = threading.Thread(target = server.serve_forever())

To be this:

thread = threading.Thread(target = server.serve_forever)

And change this:

thread.setdaemon = True

To be this:

thread.daemon = True
like image 166
dopstar Avatar answered Oct 05 '22 06:10

dopstar