Cannot read keyboard in a loop in Python

110 Views Asked by At

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?

3

There are 3 best solutions below

0
phil On BEST ANSWER
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()
5
Taha Ali On

You're trying to use the keyboard library, but the library might not be capturing key events correctly. To detect arrow key presses, you can use the curses library instead.

Like this:

import curses

stdscr = curses.initscr()
curses.cbreak()
stdscr.keypad(1)

try:
    while True:
        key = stdscr.getch()
        if key == ord('i'):
            print("up")
        elif key == ord('k'):
            print("down")

finally:
    curses.endwin()

Also to run the script, you don't need to use sudo. Just execute python3 test.py.

1
Taha Ali On

Try this:

import keyboard

def on_key_event(e):
    if e.event_type == keyboard.KEY_DOWN:
        if e.name == 'i':
            print('up')
        elif e.name == 'j':
            print('down')

keyboard.on_press(on_key_event)

keyboard.wait('esc')  # exit key

keyboard.unhook_all()