为什么我的多线程应用程序的主线程对Ctrl + C没有响应?

OMG*_*der 7 python windows

我编写了一个多线程应用程序来监视和响应给定文件列表中的更改.我有一个Watch 获取文件大小的类,并size在第一次调用时将其设置为变量.然后,几秒钟后,它再次获取文件的大小,并将其与之前的大小进行比较,如果更改,则设置size为文件的当前大小.此外,还有一个WatchWorker类是它的子类threading.Thread.在WatchWorker这使得使用Watch类"手表"给定的文件.

现在这是真正的问题:我编写的代码正在工作,并在检测到更改时通知用户.但是当我尝试使用Ctrl+ 从应用程序退出时没有响应C.我在Windows上.

码:

import time
import threading
import os

class Watch(object):
    def __init__(self, path, time=5):
        self.path = path
        self.time = time
        self.size = os.stat(path).st_size



    def loop(self):
        while True:
            time.sleep(self.time)
            size = os.stat(self.path).st_size
            if size != self.size:
                self.size = size
                print "Change detected in file {}".format(self.path)



class Watch_Worker(threading.Thread):
    def __init__(self, path, *args, **kwargs):
        super(Watch_Worker, self).__init__(*args, **kwargs)
        self.path = path


    def run(self):
        super(Watch_Worker, self).run()
        Watch(self.path).loop()

def main(*args):
    for i in args:
        thrd = Watch_Worker(path=i)
        thrd.start()
        print 'Watching ' + i
        print "From main thread"



if __name__ == '__main__':
    main('blah.js', 'cs.c', 'ab.rb')
Run Code Online (Sandbox Code Playgroud)

编辑

修改代码以比较生成的值os.stat('somefile.ext').st_size).

OMG*_*der 1

我通过设置解决了主线程无法退出的问题self.daemon = True。主线程不等待线程退出。这是通过在函数末尾添加无限while循环来解决的。这是代码:time.sleep(5)main

class Watch_Worker(threading.Thread):
        def __init__(self, path, time=2,  *args, **kwargs):
            super(Watch_Worker, self).__init__(*args, **kwargs)
            self.path = path
            self.time = time
            self.size = os.stat(path).st_size
            self.daemon = True


        def run(self):
            super(Watch_Worker, self).run()
            while True:
                time.sleep(self.time)
                size = os.stat(self.path).st_size
                if size != self.size:
                    self.size = size
                    print "Change detected in file {}".format(self.path)

    def main(*args):
        for i in args:
            thrd = Watch_Worker(path=i)
            thrd.start()
            print 'Watching ' + i
         while True:
             time.sleep(5)


    if __name__ == '__main__':
        main('blah.js', 'cs.c', 'ab.rb')
Run Code Online (Sandbox Code Playgroud)