首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >由于多线程,当键盘中断(Ctrl + C)时,我的终端不退出。有什么修复方法吗?

由于多线程,当键盘中断(Ctrl + C)时,我的终端不退出。有什么修复方法吗?
EN

Stack Overflow用户
提问于 2021-07-21 04:51:55
回答 1查看 36关注 0票数 1

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

我的代码在下面,它工作得很好,但是当我想要停止程序来测试它的but时,它不断地通过打印最后几个语句来破坏终端,同时阻止我输入。

这个问题有什么解决方法吗?

代码语言:javascript
运行
复制
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()
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-07-22 04:20:26

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

代码语言:javascript
运行
复制
    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来结束程序并再次使用终端。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68461193

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档