Python - 在Ctrl + C上杀死多个线程

时间:2012-10-14 18:33:33

标签: python

我做错了什么?

我只需要杀死Control + C上的两个线程。

def cleanup_stop_thread():
    for thread in enumerate():
        if thread.isAlive():
            try:
                self._Thread__stop()
            except:
                print(str(thread.getName()) + ' could not be terminated')

if __name__ == '__main__':  
    try:
        threading.Thread(target = record).start()
        threading.Thread(target = ftp).start()
    except (KeyboardInterrupt, SystemExit):
        cleanup_stop_thread();
        sys.exit()

2 个答案:

答案 0 :(得分:6)

不是试图在Ctrl + C上杀死它们,为什么不让它们成为守护进程?然后当主线程死亡时它们会自动退出。

t1 = threading.Thread(target=record)
t1.daemon = True
t1.start()

t2 = threading.Thread(target=ftp)
t2.daemon = True
t2.start()

答案 1 :(得分:0)

如果要在键入CTRL + C时终止所有线程,只需添加一个try块并导入os 当你想杀死一切时,做os._exit(0) 还要检查atexit模块

希望它有所帮助:)

相关问题