2009-10-29 18 views
13

Estoy usando Python 2.5 y tratando de usar un excepthook autodefinido en mi programa. En el hilo principal funciona perfectamente bien. Pero en un subproceso iniciado con el módulo de subprocesamiento se llama el excepthook habitual.'sys.excepthook' y subprocesamiento

Aquí hay un ejemplo que muestra el problema. Descomentario el comentario muestra el comportamiento deseado.

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() 

Entonces, ¿cómo puedo usar mi propio excepthook en una conversación?

Respuesta

9

Parece que hay un error relacionado reportado here con soluciones provisionales. Los hacks sugeridos básicamente envuelven run en try/catch y luego llaman sys.excepthook(*sys.exc_info())

+1

Gracias - la tercera solución funciona a la perfección! – Sebastian

8

Parece que este error todavía está presente en (al menos) 3.4, y una de las soluciones en el debate Nadia Alramli vinculada parece funcionar en Python 3.4 también.

Por conveniencia y para la documentación, voy a publicar el código para (en mi opinión) la mejor solución aquí. Actualicé el estilo de codificación y comento un poco para que sea más PEP8 y 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 
Cuestiones relacionadas