我有这个简单的http服务器,我想定义单独的线程,在循环中运行这个小代码:
while True:
time.sleep(10)
print "I am running ok."
原始代码:
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
class S(BaseHTTPRequestHandler):
def log_message(self, format, *args):
return
def _set_headers(self):
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
def do_HEAD(self):
self._set_headers()
def do_POST(self):
self._set_headers()
def run(server_class=HTTPServer, handler_class=S, port=PORT):
server_address = ('', port)
httpd = server_class(server_address, handler_class)
httpd.serve_forever()
if __name__ == "__main__":
from sys import argv
if len(argv) == 2:
run(port=int(argv[1]))
else:
run()
我应该在哪里/如何在我的代码中使用单独的线程包含这个While循环?
答案 0 :(得分:0)
将其包裹在函数中并将其传递给threading.Thread()
。
def foo():
while True:
time.sleep(10)
print ("I am running ok.")
if __name__ == "__main__":
t = threading.Thread (target=foo)
t.start()
...