由于多线程,当我键盘中断 (Ctrl + C) 时,我的终端不会退出。任何修复?

My terminal does not exit when I keyboard interrupt (Ctrl + C) due to multithreading. Any Fixes?

我以前在堆栈溢出上看到过这个问题,但它似乎不起作用,而且该解决方案已有 4 年历史,所以可能已经过时了?

我的代码在下面并且工作正常,但是当我想停止程序以测试它是否有错误时,它不断地通过打印最后几条语句来破坏终端,同时阻止我输入。

是否解决了这个问题?

from threading import Thread
import time

try:

    uInput = ""

    counter = 3

    thread_running = True


    def passwordInputting():
        global counter
        start_time = time.time()
        while time.time() - start_time <= 10:
            uInput = input()
            if uInput != "password":
                print("Incorrect Password.", counter, "tries remaining.")
                counter -= 1
                                    
            else:
                # code for if password is correct
                break

    def passwordTimer():

        global thread_running
        global counter

        start_time = time.time()
        last_time = time.time()

        # run this while there is no input or user is inputting
        while thread_running:
            time.sleep(0.1)
            if time.time() > last_time + 1:
                print("Counter:", int(time.time() - start_time))
                last_time = time.time()
            if time.time() - start_time >= 10:
                if uInput == "password":
                    continue
                else:
                    if counter > 0:
                        print("Incorrect Password.", counter, "tries remaining.")
                        counter -= 1
                        start_time = time.time()
                        
                    else:
                        # code for when no more tries left
                        break
                    
    timerThread = Thread(target=passwordTimer)
    inputThread = Thread(target=passwordInputting)

    timerThread.start()
    inputThread.start()

    inputThread.join() # interpreter will wait until your process get completed or terminated
except:
    print("Keyboard Manual Interrupt. Ege is Gay")
thread_running = False

print("Program Finished")
exit()

在启动线程之前编写一行代码,将守护进程设置为 True 可以解决此问题。

    timerThread = Thread(target=passwordTimer)
    inputThread = Thread(target=passwordInputting)

    timerThread.daemon = True
    inputThread.daemon = True 

    timerThread.start()
    inputThread.start()

    inputThread.join() # interpreter will wait until your process get completed or terminated

这些行使您可​​以按 ctrl + C 随意结束程序并再次使用终端。