skip to Main Content

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?

2

Answers


  1. 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.

    Login or Signup to reply.
  2. 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()
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search