Search code examples
pythonpython-keyboard

Cannot read keyboard in a loop in Python


I need a Python script to read arrow keys and react to them.

As a first test:

import keyboard
import time

while True:
 if keyboard.is_pressed("i"):
  print("up")
 if keyboard.is_pressed("k"):
  print("down")
 time.sleep(0.1)

It never prints "up" but, prints characters:

i
i
j
^[[A
^[[D
^[[C

I run the script in debian terminal:

sudo python3 test.py 

I expect up or down to show up in the terminal.

What am I missing?


Solution

  • from pynput import keyboard
    
    def on_key_press(key):
        try:
            # Print the key that was pressed
            print(f'Key {key} pressed')
        except AttributeError:
            # Some special keys may not have a name attribute
            print(f'Special key {key} pressed')
     
    def on_key_release(key):
        try:
            # Print the key that was released
            print(f'Key {key} released')
        except AttributeError:
            # Some special keys may not have a name attribute
            print(f'Special key {key} released')
     
    # Create a keyboard listener
    listener = keyboard.Listener(on_press=on_key_press, on_release=on_key_release)
    
    # Start listening for keyboard events
    
    listener.start()
    
    # Keep the listener running
    
    listener.join()