2014-01-14 2 views
0

현재 ssh/telnet 라이브러리를 사용하는 스레드 목록과 관련된 문제를 다루고 있습니다. 주 스레드에 대한 일부 시간 초과 값에서 스레드가 모든 리소스를 닫고 자체 종료하도록 지시하고 싶습니다. 여기에 내가하고 싶은 무엇 내 코드리소스를 닫기 위해 스레드를 가르치십시오.

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 
+0

두 번째 닫기 블록에서 스레드를 죽이기 위해''on signal''을 원하십니까? – wnnmaw

답변

0

에 같은 작업을 수행하도록 스레드 방법을 스레드를 신호를 수정할 수있는 몇 가지 방법이있다이다 UNIX에서는 다음과 같은 대답을 사용할 수 있습니다. Timeout function if it takes too long to finish

Windows에서는 더 이상 signal lib가 아니기 때문에 좀 더 까다 롭습니다. 어쨌든, 당신은 감시를 필요로하기 때문에 제한 시간은 정확하지 않습니다 http://docs.python.org/2/library/socket.html#socket.socket.settimeout

: 당신이 socket lib 디렉토리를 사용하는 경우

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 

또는, 그들이 비 차단 될 수있는 선택형가

관련 문제