键盘中断不';在python中,不要停止线程以继续运行

键盘中断不';在python中,不要停止线程以继续运行,python,python-3.x,multithreading,exception,keyboardinterrupt,Python,Python 3.x,Multithreading,Exception,Keyboardinterrupt,这段代码运行正常,我唯一的问题是当我需要停止代码时,我输入ctrl+c,尽管给出: for thread in threads: thread.alive = False thread.join() sys.exit(e) 在代码中,线程继续运行,比如说线程必须下载,即使在keyinterrupt之后,它仍继续下载。如何才能优雅地退出代码 这是完整的代码: try: threads = [] while len(list1) != 0:

这段代码运行正常,我唯一的问题是当我需要停止代码时,我输入ctrl+c,尽管给出:

for thread in threads:
    thread.alive = False
    thread.join()
    sys.exit(e)
在代码中,线程继续运行,比如说线程必须下载,即使在keyinterrupt之后,它仍继续下载。如何才能优雅地退出代码

这是完整的代码:

 try:
    threads = []
    while len(list1) != 0:
        while len(threads) != 4:
            time.sleep(1)
            item = list1.pop(0)
            thread = threading.Thread(target=func, args=(item, ))
            threads.append(thread)
            thread.start()
        for thread in threads:
            thread.join()
        for thread in threads:
            if not thread.is_alive():
                # get results from thread
                threads.remove(thread)
        if len(list1) == 0:
            logging.error("Nothing")
            sys.exit(1)
except KeyboardInterrupt as e:
    logging.error("Keyboard Interruption, code exiting!!")
    list1.append(item)
    logging.info(f'{item} Adding back to the list')
    # whenever there is a keyboard interrupt kill all the threads
    for thread in threads:
        thread.alive = False
        thread.join()
        sys.exit(e)
except Exception as e:
    logging.exception(f'Failed to initiate the threads : {e}')
    sys.exit(1)

我想你需要的是找到一种杀死一根线的方法。这通常是不可取的,尤其是当线程正在读取/写入文件时,或者当线程正在处理其他线程时。我建议阅读更多细节


您可以创建一个自定义线程包装器来处理安全停止线程的问题,或者如果您使用
多处理
库,您可以调用
进程.终止()
设置
线程.alive=False
将不会执行任何操作,除非线程真正关心该标志。如果要优雅地终止,需要修改目标
func
,定期检查
alive
的值,如果
False
则停止运行


或者,如果您不关心正常关闭,只想在主线程退出时退出所有线程,则可以在创建线程时将其添加到线程构造函数。

我无法打开上面提供的链接,这很奇怪,它不再起作用。我会尝试修复它。@DarcyM问题已修复。是的,这正是我想要的,daemon可以或可能会破坏我的数据。但我认为这是well@DarcyM发布目标的代码
func
——它需要检查
alive
值,当值变为false时进行清理。