Created
April 17, 2022 22:04
-
-
Save erm3nda/65a9cc4448aee2c324ab2efeb9a3ac67 to your computer and use it in GitHub Desktop.
python thread kill with ctypes
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 ctypes | |
def terminate_thread(thread): | |
"""Terminates a python thread from another thread. | |
:param thread: a threading.Thread instance | |
""" | |
if not thread.is_alive(): | |
return | |
exc = ctypes.py_object(SystemExit) | |
res = ctypes.pythonapi.PyThreadState_SetAsyncExc( | |
ctypes.c_long(thread.ident), exc) | |
if res == 0: | |
raise ValueError("nonexistent thread id") | |
elif res > 1: | |
# """if it returns a number greater than one, you're in trouble, | |
# and you should call it again with exc=NULL to revert the effect""" | |
ctypes.pythonapi.PyThreadState_SetAsyncExc(thread.ident, None) | |
raise SystemError("PyThreadState_SetAsyncExc failed") # esto solo se dispara si el anterior falla |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment