I am new to this group. Hello to everyone!

I am trying kill a thread by setting up traces in the python code.

The thread code is given below:

######################################

class KThread(threading.Thread):
"""A subclass of threading.Thread, with a kill() method."""
def __init__(self, *args, **keywords):
threading.Thread.__init__(self, *args, **keywords)
self.killed = False

def start(self):
"""Start the thread."""
self.__run_backup = self.run
self.run = self.__run # Force the Thread to install our trace.
threading.Thread.start(self)

def __run(self):
"""Hacked run function, which installs the trace."""
sys.settrace(self.globaltrace)
self.__run_backup()
self.run = self.__run_backup

def globaltrace(self, frame, why, arg):
if why == 'call':
return self.localtrace
else:
return None

def localtrace(self, frame, why, arg):
if self.killed:
if why == 'line':
raise SystemExit()
return self.localtrace

def kill(self):
self.killed = True

###################################

The main code where I am calling this class is as shown below:

def startThread(self, event):
self.keepGoing = self.running = True
#tid = thread.start_new_thread(self.onRunTest, (event,))
self.testThread = KThread(target=self.onRunTest)
self.testThread.start()
print '******************Thread Started*****************'

def kill(self, event):
self.keepGoing = False
self.testThread.kill()
print '******************Thread Stopped*****************'

#####################################

But whenever kill() is executed, it gives me the following error

18:31:44.661 - SYSTEM ERROR - Test1: Unhandled exception from test
18:31:44.661 - SYSTEM ERROR - Test1: Traceback (most recent call last):
File "C:\Python24\lib\site-packages\gtest\util\__init__.py", line 220, in run
test.start(testCase)
File "C:\Python24\lib\site-packages\gtest\util\__init__.py", line 466, in start
else:
File ".\Repeater_Main_Test_Protocol2.py", line 114, in run
gtest.util.sleep(10)
File ".\Repeater_Main_Test_Protocol2.py", line 114, in run
gtest.util.sleep(10)
File "u:\development\gtest\ui\TestRunner.py", line 682, in localtrace
raise SystemExit()
SystemExit

-------------------------------------------------------

For some reasons, it is giving me error with the use of "SystemExit".

Would anyone know the solution for killing a thread in python?

Thanking you in advance!


I would just cancel the tread.

How do you cancel the thread in Python?

This article has been dead for over six months. Start a new discussion instead.