繁体   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) 

我需要在后台运行Hello的同时运行服务器。 您能告诉我我在做什么错吗,因为如果尝试输入URL,则该页面永远不会加载。 但是,正在打印Hello并且服务器确实启动。

您需要在threading.Thread target关键字参数中传递方法test ,而不是test返回的结果。 因此,更换

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

thread1 = threading.Thread(target=test)

当您执行target=test()将立即调用测试方法,因此无限循环且请求永不返回。

暂无
暂无

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

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