import threading import sys class ExitThread(threading.Thread): def __init__(self, sys_exit_arg=None): threading.Thread.__init__(self) self.sys_exit_arg = sys_exit_arg def run(self): print " thread running." if self.sys_exit_arg: if self.sys_exit_arg == "raise": print " exit thread using `raise SystemExit, 'raised SystemExit'`" raise SystemExit, 'raised SystemExit' print (" exit thread using `sys.exit(arg)` with arg '%s' of %s." % (self.sys_exit_arg, type(self.sys_exit_arg))) sys.exit(self.sys_exit_arg) print " exit thread using sys.exit() without arg" sys.exit() def start_and_join(self): self.start() self.join() class foo(object): def __init__(self): pass print "* MainThread: Starting test thread 1..." t = ExitThread(1) t.start_and_join() print "* MainThread: Starting test thread 2..." t = ExitThread("incredibly informative error description") t.start_and_join() print "* MainThread: Starting test thread 3..." f = foo() t = ExitThread(f) t.start_and_join() print "* MainThread: Starting test thread 4..." t = ExitThread("raise") t.start_and_join() print "* MainThread: Starting test thread 5..." t = ExitThread() t.start_and_join() print "* MainThread: Exit using sys.exit() with arg '%s' of %s." % (f, type(f)) sys.exit(f) # OUTPUT with the patched version of threading.py: # ================================================ #* MainThread: Starting test thread 1... # thread running. # exit thread using `sys.exit(arg)` with arg '1' of . #* MainThread: Starting test thread 2... # thread running. # exit thread using `sys.exit(arg)` with arg 'incredibly informative error description' of . #* MainThread: Starting test thread 3... # thread running. # exit thread using `sys.exit(arg)` with arg '<__main__.foo object at 0x000000000229DDD8>' of . #* MainThread: Starting test thread 4... # thread running. # exit thread using `raise SystemExit, 'raised SystemExit'` #* MainThread: Starting test thread 5... # thread running. # exit thread using sys.exit() without arg #* MainThread: Exit using sys.exit() with arg '<__main__.foo object at 0x000000000229DDD8>' of .