我想創建一個包含兩個主機列表的程序。我想從每個主機讀取數據。這將需要大約5-10秒,所以我想用不同的線程讀取每個主機數據。Python:如何終止多線程的Python程序?
我創建了下面的代碼,它按照我的期望工作,但問題是當我按下Ctrl + c時,程序沒有終止。
我的代碼:
import threading
import time,os,sys
import signal
is_running = True
def signal_handler(signal, frame):
print "cleaning up...please wait..."
v1.stop()
v2.stop()
global is_running
is_running = False
class Thread2(threading.Thread):
def __init__(self, function,args):
self.running = False
self.function = function
self.args = args
super(Thread2, self).__init__()
def start(self):
self.running = True
super(Thread2, self).start()
def run(self):
while is_running:
self.function(self.args)
time.sleep(time_interval)
def stop(self):
self.running = False
def b_iterate(hostnames):
for host_name in hostnames:
v = Thread2(function = read_cet_data,args = host_name)
v.start()
def read_b_data(host):
#
#reading some data from current host (5-10 seconds processing)
#
#here, this thread is not neccessary, want to stop or kill or terminate it
if threading.current_thread().isAlive():
threading.current_thread().stop()
def a_iterate(entp_hostnames):
for host_name in entp_hostnames:
v = Thread2(function = read_entp_data,args = host_name)
v.start()
def read_a_data(host):
#
#reading some data from current host (5-10 seconds processing)
#
#here, this thread is not neccessary, want to stop or kill or terminate it
if threading.current_thread().isAlive():
threading.current_thread().stop()
if __name__ == "__main__":
signal.signal(signal.SIGINT, signal_handler)
#a_hostnmaes & b_hostnmaes are the lists of hostnames
v1 = Thread2(function = a_iterate,args = a_hostnames)
v2 = Thread2(function = b_iterate,args = b_hostnames)
v1.start()
v2.start()
while is_running:
pass
我怎樣才能使按Ctrl + C後,這個程序終止。我錯過了什麼嗎?
檢查:https://stackoverflow.com/questions/1112343/how-do-i-capture-sigint-in-python和https://計算器。 com/questions/18114560/python-catch-ctrl -c-command-prompt-really-want-to-quit-yn-resume-executi – Drako
@ Drako-我檢查了它。由於多線程,我的程序沒有終止。我如何通知它終止。 – kit
對不起,我從來沒有需要任何多線程,只是輕量級的應用程序,在1線程運行良好:) - 沒有經驗,只是希望這些鏈接可以幫助想法 – Drako