Skip to content

Instantly share code, notes, and snippets.

@Jerry0420
Last active May 3, 2022 03:13
Show Gist options
  • Save Jerry0420/5fb0fc2cba3283a8740cae6a3bc81d72 to your computer and use it in GitHub Desktop.
Save Jerry0420/5fb0fc2cba3283a8740cae6a3bc81d72 to your computer and use it in GitHub Desktop.
Python Killable Thread
import threading
import sys
class KillableThread(threading.Thread):
def __init__(self, *args, **keywords):
threading.Thread.__init__(self, *args, **keywords)
self.killed = False
def start(self):
self.__run_backup = self.run
self.run = self.__run
threading.Thread.start(self)
def __run(self):
sys.settrace(self.globaltrace)
self.__run_backup()
self.run = self.__run_backup
def globaltrace(self, frame, event, arg):
if event == 'call':
return self.localtrace
else:
return None
def localtrace(self, frame, event, arg):
if self.killed:
if event == 'line':
raise SystemExit()
return self.localtrace
def kill(self):
self.killed = True
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment