简体   繁体   English

如何在python中在后台运行线程

[英]How to run a thread in the background in python

 class CORSRequestHandler (SimpleHTTPRequestHandler): def do_GET(self): thread1 = threading.Thread(target=test()) thread1.daemon = True thread1.start() return SimpleHTTPRequestHandler.do_GET(self) def test(): while True: print "Hello" time.sleep(2) if __name__ == '__main__': BaseHTTPServer.test(CORSRequestHandler, BaseHTTPServer.HTTPServer) 

I need to run a server meanwhile printing Hello in the background. 我需要在后台运行Hello的同时运行服务器。 Can you please tell me what i am doing wrong because if a try to enter the url the page never loads up. 您能告诉我我在做什么错吗,因为如果尝试输入URL,则该页面永远不会加载。 However Hello is being printed and the server does start. 但是,正在打印Hello并且服务器确实启动。

You need to pass method test in target keyword argument of threading.Thread , not what test returns. 您需要在threading.Thread target关键字参数中传递方法test ,而不是test返回的结果。 So, replace 因此,更换

thread1 = threading.Thread(target=test())

with

thread1 = threading.Thread(target=test)

When you do target=test() test method is called right then, hence the infinite loop and the request never returns. 当您执行target=test()将立即调用测试方法,因此无限循环且请求永不返回。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM