Skip to content

Instantly share code, notes, and snippets.

@justfoolingaround
Created April 11, 2022 12:23
Show Gist options
  • Save justfoolingaround/ea136d7c515050a543323852e74961d4 to your computer and use it in GitHub Desktop.
Save justfoolingaround/ea136d7c515050a543323852e74961d4 to your computer and use it in GitHub Desktop.
Be able kill Python threads by installing a trace
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