0
我正在使用一個線程來創建一個可中斷的,當按下特定鍵時發送KeyboardInterrupt命令。在這個過程之後,我再次使用msvcrt.getch()函數。問題是線程不會退出,直到我按下一次該鍵。即倒計時功能完成,但線程仍在等待msvcrt.getch()函數的輸入。python中的特定線程退出
我試着把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"
http://stackoverflow.com/questions/2757318/how-do-i-read-user-input-in-python-thread –
'我需要,而不是使用線程的線程?'是的。 'threading'是高級API,'thread'是低級的。 – roippi
使用t = threading.Thread(target = input_thread) – w5e