SimpleHTTPServer launched as a thread: does not daemonize
Asked Answered
C

2

12

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?

Creature answered 5/2, 2015 at 16:54 Comment(1)
thread = threading.Thread(target = server.serve_forever)Telly
H
13

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
Hypanthium answered 6/2, 2015 at 11:27 Comment(1)
I bet this was a typo. thread.setDaemon(True) is also possible.Conform
L
3

Try thread = threading.Thread(target = server.serve_forever), i.e. without the call.

The problem with your version is that serve_forever() is called on parsing the line where the thread is created. Thus, you never get to the next line.

The argument type must be callable, which will be called on thread start, so you need to pass name, server.serve_forever instead of trying to pass result of executing this function.

Loriannlorianna answered 6/2, 2015 at 11:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.