Last active
May 3, 2022 03:13
-
-
Save Jerry0420/5fb0fc2cba3283a8740cae6a3bc81d72 to your computer and use it in GitHub Desktop.
Python Killable Thread
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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