Skip to main content
 首页 » 编程设计

python之如何杀死 Python 中的主线程

2025年05月04日14开发

如何杀死主线程并终止程序? 现在抛出 RuntimeError 主线程继续执行

def function_terminate(): 
    raise RuntimeError 
 
def test(): 
    thr = threading.Timer(5.0, function_terminate, args=()) 
    thr.start() 
    setup() 
    sleep(6) 
    thr.cancel() 
    continue_code() 

我不能使用 thread.interrupt_main()来自 this问题是因为我使用的是 threading 模块而不是 thread

非常感谢你的帮助

请您参考如下方法:

您可以 os._exit(n) ,这会导致整个过程退出(以一种不干净的方式)。但是,您通常没有理由终止主线程。