由于多线程,当键盘中断(Ctrl+C)时,我的终端不会退出.有修复吗



我以前见过这个关于堆栈溢出的问题,但它似乎不起作用,而且解决方案已经有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任意结束程序,然后再次使用终端。

相关内容

  • 没有找到相关文章

最新更新