我以前在堆栈溢出上见过这个问题,但它似乎不起作用,而且解决方案已经有4年的历史了,所以它可能已经过时了?
我的代码在下面,它工作得很好,但是当我想要停止程序来测试它的but时,它不断地通过打印最后几个语句来破坏终端,同时阻止我输入。
这个问题有什么解决方法吗?
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()发布于 2021-07-22 04:20:26
在启动线程之前编写一行代码将守护进程设置为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来结束程序并再次使用终端。
https://stackoverflow.com/questions/68461193
复制相似问题