python下使用threading的多线程程序处理SIGINT(Ctrl+C)

我的多线程程序如下:

需要注意的是fetcher类,继承threading.Thread类在初始化的时候将信号注册一下就OK了。

不然按下Ctrl+C终止的是当前的thread,不会终止所有的thread

class fetcher(threading.Thread):

    def __init__(self, fname, outdir, url):

        threading.Thread.__init__(self)

        signal.signal(signal.SIGINT, sigquit)

        signal.signal(signal.SIGTERM, sigquit)

        self.fname = fname

        self.outdir = outdir.replace("|", "_")

        self.outdir = self.outdir.replace("\\", "")

        

        self.url = url

        if not os.access(self.outdir, os.R_OK):

            os.mkdir(self.outdir)

    

    def run(self):

        ftype = self.url.split('.')[-1]

        fn = ''.join((self.outdir, "/", self.fname, ".", ftype))

        self.get_pic(self.url, fn)

    

    def get_pic(self, url, output):

        command = "wget -q %s -O %s"%(url, output)

        print url

        os.system(command)

def fetch(works):

    threads=[]

    for work in works:

        thr = fetcher(work[0], work[1], work[2])

        thr.start()

        threads.append(thr)

#    for thr in threads:

#        thr.join()

    while threading.active_count() > 1:

        time.sleep(0.1)


def sigquit(sig, frame) :

    """ signal function of exit

    """

    print "recieved a exit signal!!!"

    sys.exit(0)


你可能感兴趣的:(python下使用threading的多线程程序处理SIGINT(Ctrl+C))