python中的特定线程退出

时间:2014-05-16 22:48:47

标签: python multithreading

我正在使用一个线程来创建一个可中断的,当按下一个特定的键时,它会发送KeyboardInterrupt命令。在此过程之后,我再次使用msvcrt.getch()函数。问题是线程不会退出,直到我按下一次键。即倒计时函数完成但线程仍在等待msvcrt.getch()函数的输入。

我尝试将exit.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 :(得分: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")