2014-05-16 4 views
0

스레드를 사용하여 특정 키를 누를 때 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" 
+0

http://stackoverflow.com/questions/2757318/how-do-i-read-user-input-in-python-thread –

+0

'내가 대신 스레드의 스레딩 사용해야합니까?'네. 'threading'는 하이 레벨 API이고'thread'는 로우 레벨입니다. – roippi

+0

사용 t = threading.Thread (target = input_thread) – w5e

답변

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")