def _sketch_raise_in_main(exc):
''' Sketchy way to raise an exception in the main thread.
'''
if isinstance(exc, BaseException):
exc = type(exc)
elif issubclass(exc, BaseException):
pass
else:
raise TypeError('Must raise an exception.')
# Figure out the id of the main thread
main_id = threading.main_thread().ident
thread_ref = ctypes.c_long(main_id)
exc = ctypes.py_object(exc)
result = ctypes.pythonapi.PyThreadState_SetAsyncExc(
thread_ref,
exc
)
# 0 Is failed.
if result == 0:
raise SystemError('Main thread had invalid ID?')
# 1 succeeded
# > 1 failed
elif result > 1:
ctypes.pythonapi.PyThreadState_SetAsyncExc(main_id, 0)
raise SystemError('Failed to raise in main thread.')
评论列表
文章目录