2017-12-13 3 views
0

파이썬 스크립트에서 나는 계속해서 함수를 호출하고 동시에 ESC 키를 누른 사용자의 말을 듣고 싶습니다. 프로그램을 종료하십시오.Python의 독립적 인 (비 블로킹) 스레드에서 키 누르기 감지하기

이 내 현재 코드입니다 : 어떤 키를 누를 때까지 thread_2thread_1 블록 것처럼 보인다 그러나

import threading 
import msvcrt 

def wait_for_esc(): 
    while True: 
    key = ord(msvcrt.getch()) 
    if key == 27: 
     print("ESC") 
     exit(0) 

def do_something(): 
    while True: 
    call_function() 

thread_1 = threading.Thread(name="wait_for_esc", target=wait_for_esc()) 
thread_2 = threading.Thread(name="do_something", target=do_something()) 

thread_1.start() 
thread_2.start() 

.

두 스레드를 각각 독립적으로 실행할 수있는 가능한 솔루션은 무엇입니까?

답변

1

대상 작업을 스레드에 전달할 때 함수 개체를 전달해야합니다. 함수를 호출하면 안됩니다. 함수 이름 끝에 paranthesis를 제거해야합니다.

thread_1 = threading.Thread(name="wait_for_esc", target=wait_for_esc) 
thread_2 = threading.Thread(name="do_something", target=do_something) 

그리고 제대로 작동합니다.