123456789101112131415161718192021222324252627282930313233343536373839import ctypesimport inspectimport timefrom threading import Threaddef _async_raise(tid, exctype): tid = ctypes.c_long(tid) if not inspect.isclass(exctype): exctype = type(exctype) res = ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, ctypes.py_object(exctype)) if res == 0: raise ValueError("invalid thread id") elif res != 1: ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, None) raise SystemError("PyThreadState_SetAsyncExc failed")def stop_thread(thread): print(f'\nt -> {thread}') print(f'\nthread.ident -> {thread.ident}') _async_raise(thread.ident, SystemExit) thread.join()def func1(): while True: try: print(f'func1') time.sleep(1) except SystemExit: print("!!!!") sys.exit() except: print(traceback.format_exc())i = Thread(target=func1, args=())i.start()time.sleep(3)print(f'线程{i}的状态{i.is_alive()}, 线程{i}的名字{i.name}, 线程的方法{i.ident}')print(type(i.name), i.name)stop_thread(i)