“sys.excepthook”和线程

2024-04-26 09:52:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用Python2.5并试图在我的程序中使用自定义的excepthook。在主线程中,它工作得非常好。但是在以线程模块开始的线程中,通常的excepthook被调用。

下面是一个显示问题的示例。取消注释注释将显示所需的行为。

import threading, sys

def myexcepthook(type, value, tb):
    print 'myexcepthook'

class A(threading.Thread, object):

    def __init__(self):
        threading.Thread.__init__(self, verbose=True)
#       raise Exception('in main')
        self.start()

    def run(self):
        print 'A'
        raise Exception('in thread')            

if __name__ == "__main__":
    sys.excepthook = myexcepthook
    A()

那么,如何在线程中使用自己的excepthook


Tags: inself程序initmaindefsysexception
2条回答

看起来这个bug仍然存在于(至少)3.4中,Nadia Alramli链接的讨论中的一个解决方法似乎也适用于Python 3.4。

为了方便和文档,我将在这里(以我的观点)发布代码以获得最佳解决方案。我稍微更新了编码风格和注释,使之更像PEP8和Pythonic。

import sys
import threading

def setup_thread_excepthook():
    """
    Workaround for `sys.excepthook` thread bug from:
    http://bugs.python.org/issue1230540

    Call once from the main thread before creating any threads.
    """

    init_original = threading.Thread.__init__

    def init(self, *args, **kwargs):

        init_original(self, *args, **kwargs)
        run_original = self.run

        def run_with_except_hook(*args2, **kwargs2):
            try:
                run_original(*args2, **kwargs2)
            except Exception:
                sys.excepthook(*sys.exc_info())

        self.run = run_with_except_hook

    threading.Thread.__init__ = init

似乎有一个相关的bug报告了here和解决方法。建议的技巧基本上是在try/catch中包装run,然后调用sys.excepthook(*sys.exc_info())

相关问题 更多 >