作为线程启动的SimpleHTTPServer:不守护 [英] SimpleHTTPServer launched as a thread: does not daemonize

查看:92
本文介绍了作为线程启动的SimpleHTTPServer:不守护的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在单独的线程中启动SimpleHTTPServer,同时在主线程中执行其他操作(此处为time.sleep(100)).这是我的代码的简化示例:

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)

但是,线程保持阻塞"状态,即未作为守护程序启动,并且解释器未到达print 'OK'.它既不会到达STUCK HERE.

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.

尽管我只有在调用threading.Thread(...)时才会初始化该线程,并且主线程仍会走得更远,直到找到thread.start指令来启动它.

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?

推荐答案

更改此内容:

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

要成为这样:

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

并更改此内容:

thread.setdaemon = True

要成为这样:

thread.daemon = True

这篇关于作为线程启动的SimpleHTTPServer:不守护的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆