Python中特定线程退出

0 投票
1 回答
1420 浏览
提问于 2025-04-18 06:49

我正在使用一个线程来创建一个可以被打断的功能,当我按下特定的键时,它会发送一个KeyboardInterrupt命令。在这个过程之后,我又使用了msvcrt.getch()这个函数。问题是,线程在我按下那个键之前是不会退出的。也就是说,倒计时的功能完成了,但线程仍然在等待msvcrt.getch()函数的输入。

我尝试在倒计时函数的最后加上exit.thread(),但这样会导致主线程退出。我是不是需要用threading而不是thread呢?

import time, thread, msvcrt

print "enter time for timer"
n=raw_input()

def input_thread():
    z=msvcrt.getch()
    if z == "a" :   
        thread.interrupt_main()
    if z != "a" :
        thread.start_new_thread(input_thread, ())
        print "nope"
        thread.exit()

def countdown(n):
    try:
        thread.start_new_thread(input_thread, ())
        for i in range(int(n)):
            c = int(n) - int(i)
            print c ,'seconds left','\r',
            time.sleep(1)

    except KeyboardInterrupt:
        print "I was rudly interrupted"

countdown(n)
print """

"""
k=msvcrt.getch()
if k == "k" :
    print "you typed k"
else :
    print "you did not type K"

1 个回答

0

这不是最优雅的方法,但它能奏效。

from concurrent.futures import thread
import threading
import time, msvcrt

print("enter time for timer")
n=input()

def input_thread():
   z=msvcrt.getch()
   if z == "a" :
       thread.interrupt_main()
   if z != "a" :
       thread.start_new_thread(input_thread, ())
       print ("nope")
       thread.exit()

def countdown(n):
try:
    threading.Thread(target=input_thread)
    for i in range(int(n)):
        c = int(n) - int(i)
        print (c ,'seconds left','\r')
        time.sleep(1)

except KeyboardInterrupt:
    print("I was rudly interrupted")

countdown(n)
print ("")
k=msvcrt.getch()
if k == "k" :
    print("you typed k")
else :
    print ("you did not type K")

撰写回答