Created
April 11, 2022 12:23
-
-
Save justfoolingaround/ea136d7c515050a543323852e74961d4 to your computer and use it in GitHub Desktop.
Be able kill Python threads by installing a trace
This file contains hidden or 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 sys | |
import threading | |
class DeathThread(threading.Thread): | |
kill_state = threading.Event() | |
def run(self): | |
sys.settrace(self.global_trace) | |
return super().run() | |
def global_trace(self, stack_frame, reason, *args, **kwargs): | |
if reason == "call": | |
return self.local_trace | |
def local_trace(self, stack_frame, reason, *args, **kwargs): | |
if self.kill_state.is_set() and reason == "line": | |
raise SystemExit() | |
return self.local_trace | |
def kill(self): | |
return self.kill_state.set() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment