Pythonic方式知道我的线程退出的时间/原因

时间:2013-09-03 19:57:30

标签: python multithreading python-2.6

上下文 我有一个无限运行的脚本,它监视一个需要下载的URL的简单队列。如果一个url进入队列,脚本会检查它是否已经为该url生成了一个线程,如果没有,它会生成一个线程,该线程的工作是定期从该url获取数据,直到url将其返回404(我知道会发生,因为网址仅在指定的时间段内可用),此时,它会调用sys.exit来引发SystemExit例外,并根据我的理解将其标记为终止。

问题我希望能够记录线程退出时的具体时间,即使除了我sys.exit之外的其他原因退出并收集尽可能多的元数据关于它为何尽可能退出的数据。做这个的最好方式是什么?线程是否将信息传递给退出时产生它们的父级?

代码:

代码的简化示例

    class MyThread(threading.Thread):
        def __init__(self, sF, id):
            threading.Thread.__init__(self)
            self.sourceFile = [sF]
            self.id = id 

        def run(self): 
            #do stuff until i encounter a 404, at which point, I'll call sys.exit

if __name__ == '__main__':
    while True: 
        #logic to check the queue, if there is a new url, spawn a new Thread
        #for each new thread in the queue: 
            t = MyThread(file, i)
            t.start()
            threads.append(t) 

1 个答案:

答案 0 :(得分:5)

这样做:

import datetime

class MyThread(threading.Thread)
    termination_cause = None
    termination_time = None

    #snip

    def run(self):
        try:
            # do stuff
        except Exception as e:  # I wouldn't recommend this, but you asked for it
            self.termination_cause = e  # If an Exception occurred, it will be here
        finally:
            self.termination_time = datetime.datetime.now()

一旦退出try块,无论是因为Exception被引发还是因为块结束,那么finally块将会执行,termination_time属性将被设置。


请注意,我不认为提高SystemExit以关闭您的主题是一种好习惯。你为什么不把这个块流到它的最后?

def run(self):
    try:
        while 1:
            if url_returns_404(url):
                break
            # do my thing with the URL
    finally:
        self.termination_time = datetime.datetime.now()