2009-10-29 31 views
13

我正在使用Python 2.5并试图在我的程序中使用自定义的excepthook。在主线程中它工作得很好。但是在线程模块启动的线程中,调用通常的excepthook'sys.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

回答

9

它看起来像有一个相关的错误报告here与解决方法。建议的hack基本上是在try/catch中运行,然后调用sys.excepthook(*sys.exc_info())

+1

感谢 - 第三个解决方法完美地工作! – Sebastian 2009-10-29 12:42:11

8

看起来像这个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