Robert Strauch
Robert Strauch

Reputation: 12896

Detecting key press in independent (non-blocking) thread in Python

In a Python script I'd like to continiously call a function and, at the same time, listen for the user having pressed the ESC key which would then exit the program.

This is my current code:

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

However it seems as if thread_1 blocks thread_2 until any key has been pressed.

What's a possible solution to run both thread independent from each other?

Upvotes: 1

Views: 223

Answers (1)

Chen A.
Chen A.

Reputation: 11280

When you pass in the target task to the thread, you need to pass the function object - not call the function. You need to remove the paranthesis at the end of your function name.

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

And it should work.

Upvotes: 2

Related Questions