我目前正在处理一个问题,涉及所有使用 ssh/telnet libs 的线程列表。我希望主线程在某个超时值指示线程关闭其所有资源并自行终止。下面是我的代码的示例
import threading
import time
import socket
threads = []
def do_this(data):
"""this function is not the implementation this code may not be valid"""
w = socket.create_connection(data, 100)
while True:
if 'admin' in w.read(256):
break
w.close
for data in data_list:
t = threading.Thread(target=do_this, args=(data,))
t.start()
threads.append(t)
end_time = time.time()+120
for t in threads:
t.join(end_time-time.time())
我想做的是有一些方法来向线程发出信号并修改线程方法,以便它做这样的事情
def do_this(data):
w = socket.create_connection(data, 100)
while True:
if 'admin' in w.read(256):
break
w.close()
on signal:
w.close()
return
在UNIX上,您可以使用以下答案: 超时功能(如果完成时间太长)
在Windows上,它有点棘手,因为这不是signal
库。无论如何,你只需要一个看门狗,所以超时不必精确:
def timeout(timeout):
sleep(XX_SECONDS)
timeout = True
def do_this(data):
"""this function is not the implementation this code may not be valid"""
timeout = False
w = socket.create_connection(data, 100)
timer = threading.Thread( target = timeout, args=(timeout,) )
while not timeout:
if 'admin' in w.read(256):
break
或者,如果您使用的是socket
库,则可以选择非阻塞:http://docs.python.org/2/library/socket.html#socket.socket.settimeout