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
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 thecurses
library instead.Like this:
Also to run the script, you don’t need to use
sudo
. Just executepython3 test.py
.Try this: