[英]Python, Stop a Thread
我正在嘗試創建一個可ping通IP地址並記錄連接時間/未連接時間的類。
由於此類是GUI的一部分,因此我希望在用戶詢問時停止此線程。
找到了一些Q&A來解決此問題,但實際上沒有一個導致線程停止。
我正在嘗試制作一個方法,該類的一部分將停止self.run()
這是我的Pinger
課:
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
在線程應退出時向您發出信號。 這樣,您可以公開事件並讓其他線程對其進行設置,同時可以從線程內檢查事件的狀態並根據請求退出。
在您的情況下,它可能很簡單:
class Pinger(threading.Thread):
def __init__(self, address='', rate=1):
threading.Thread.__init__(self)
self.kill = threading.Event()
# the rest of your setup...
# etc.
def start_ping(self):
self.timestamp = datetime.datetime.now()
while not self.kill.is_set():
# do your pinging stuff
# etc.
然后,每當您希望線程停止運行時(例如從UI中停止),只需對其進行調用: pinger_instance.kill.set()
就可以了。 請記住,壽,這將需要一段時間才能得到殺害,由於阻塞os.system()
調用,由於time.sleep()
你必須在你的最后Pinger.start_ping()
方法。
使用_Thread_stop():
MyPinger._Thread__stop()
我將對您的類進行一些編碼,以使其作為守護程序運行。
保留start_ping代碼,然后使用下一個代碼:
MyPinger = threading.Thread(target = self.start_ping, name="Pinger")
MyPinger.setDaemon(True)
MyPinger.start() # launch start_ping
並可能使用_Thread_stop()停止它,這有點殘酷...:
if MyPinger.IsAlive():
MyPinger._Thread__stop()
感謝@zwer的帶頭。 這是我完整的代碼(已標記更改)
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
self.event = threading.Event() # <---- Added
def run(self):
while not self.event.is_set(): # <---- Added
self.start_ping()
self.event.wait(self.ping_rate) # <---- Added ( Time to repeat moved in here )
def stop(self): # <---- Added ( ease of use )
self.event.set() # <---- Added ( set to False and causes to stop )
def start_ping(self):
self.timestamp = datetime.datetime.now()
# While loop ##--- > Deleted. now it loops in run method #####
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) # <---- deleted
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]
def get_status(self):
return self.last_status
c = Pinger('127.0.0.1', 5)
c.start()
time.sleep(10)
c.stop()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.