IP 주소를 핑 (ping)하고 연결된/연결되지 않은 시간에 대한 레코드를 유지하는 클래스를 만들려고합니다.Python, 스레드 중지
이 클래스는 GUI의 일부이므로 사용자가 물어볼 때이 스레드를 중지하고 싶습니다.
발견 된 일부 Q &이 문제를 해결했지만 어느 것도 실제로 스레드를 중지시키지 않습니다.
나는 방법, 여기 내 Pinger
클래스의 self.run()
중지됩니다이 클래스의 일부를 만들려고 노력 해요 :
class Pinger(threading.Thread):
def __init__(self, address='', rate=1):
threading.Thread.__init__(self)
self.address = address
self.ping_rate = rate
self.ping_vector, self.last_ping = [], -1
self.start_time, self.last_status = datetime.datetime.now(), []
self.timestamp, self.time_vector = 0, [datetime.timedelta(0)] * 4
def run(self):
self.start_ping()
def start_ping(self):
self.timestamp = datetime.datetime.now()
while True:
ping_result = os.system('ping %s -n 1 >Null' % self.address)
self.ping_vector.append(ping_result)
if self.last_ping != ping_result:
text = ['Reachable', 'Lost']
print(str(self.timestamp)[:-4], self.address, text[ping_result])
round_time_qouta = datetime.datetime.now() - self.timestamp
self.timestamp = datetime.datetime.now()
self.update_time_counter(ping_result, round_time_qouta)
self.last_ping = ping_result
time.sleep(self.ping_rate)
def update_time_counter(self, ping_result=0, time_quota=datetime.timedelta(0)):
"""self.time_vector = [[cons.succ ping time],[cons.not_succ ping time],
[max accum succ ping time],[max accum not_succ ping time] """
p_vec = [0, 1]
self.time_vector[p_vec[ping_result]] += time_quota
if self.time_vector[p_vec[ping_result]].total_seconds() > self.time_vector[
p_vec[ping_result] + 2].total_seconds():
self.time_vector[p_vec[ping_result] + 2] = self.time_vector[p_vec[ping_result]]
self.time_vector[p_vec[ping_result - 1]] = datetime.timedelta(0)
self.last_status = [ping_result, self.chop_milisecond(self.time_vector[ping_result]),
self.chop_milisecond(self.time_vector[ping_result + 2]),
self.chop_milisecond(datetime.datetime.now() - self.start_time)]
print(str(self.timestamp)[:-4], "State: " + ['Received', 'Lost'][ping_result],
" Duration: " + self.last_status[1], " Max Duration: " + self.last_status[2],
"Total time: " + self.last_status[3])
def chop_milisecond(self, time):
return str(time).split('.')[0]
사용 ['threading.Event'] (https://docs.python.org/2/library/threading.html#event-objects) 신호에의하여 스레드가 종료해야하는 경우 스레드를 설정하고 이벤트가 설정된 경우 스레드에서 주기적으로 검사를 수행 한 다음 종료하십시오. – zwer
@zwer 코드로 설명 할 수 있습니까? –