简体   繁体   中英

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. Can you please tell me what i am doing wrong because if a try to enter the url the page never loads up. However Hello is being printed and the server does start.

You need to pass method test in target keyword argument of threading.Thread , not what test returns. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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