0

I'm testing this code from this response However I'm getting nothing in my output! Does anyone know why? My goal is to have a loop start when a key is pressed down and end when it's released. For some reason I can't get it to work.

from pynput.keyboard import Listener, KeyCode
import time

# --- functions ---

def get_pressed(event):
    global key_a # inform function to use external/global variable instead of local one

    if event == KeyCode.from_char('a'):
        key_a = True

def get_released(event):
    global key_a

    if event == KeyCode.from_char('a'):
        key_a = False

# --- main --

key_a = False  # default value at start 

listener = Listener(on_press=get_pressed, on_release=get_released)
listener.start() # start thread with listener

while True:

    if key_a:
        print('hold pressed: a')

    time.sleep(.1)  # slow down loop to use less CPU

listener.stop() # stop thread with listener
listener.join() # wait till thread ends work
Cal Sal
  • 1
  • 1
  • I would guess that the keycode is just one attribute of the event object being passed to your listener functions, rather than something that's *equal* to the event object. – jasonharper Feb 28 '21 at 07:12
  • The code looks OK. If you add `print` calls in the two event handlers, do you ever get hits? – Tim Roberts Feb 28 '21 at 07:25
  • Just checking -- you realize this is not a system-wide hook, right? This will only catch keys that you press when your terminal session has the focus. – Tim Roberts Feb 28 '21 at 07:27

0 Answers0