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

Bra*_*rad 2 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) 
Run Code Online (Sandbox Code Playgroud)

Tho*_*zco 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()
Run Code Online (Sandbox Code Playgroud)

一旦退出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()
Run Code Online (Sandbox Code Playgroud)