0

I am trying to control a robot with the keyboard. I want to get the user input from the keyboard and call the respective function, it could be the letters "l" for left, "r" for right and "e" for exit.

direction = ""
while direction != "e":
    direction = input("enter direction: ")
    if direction == "r":
        goRight()
    elif direction == "l":
        goLeft()

The code is working but the user have to type the enter key each time. Is there a solution to read the key immediately when typed?

laieman
  • 181
  • 1
  • 1
  • 8
  • 1
    What about [this](https://stackoverflow.com/questions/510357/how-to-read-a-single-character-from-the-user)? I think [pygame](https://stackoverflow.com/questions/16044229/how-to-get-keyboard-input-in-pygame) offers something similar as well. – DevConcepts Sep 27 '21 at 10:36

1 Answers1

1

Try readchar. It's really simple but should fit your needs:

Simple example

import readchar 

while True:
    key = readchar.readkey()
    print(key)

Implemented in your function

direction = ""
while direction != "e":
    direction = readchar.readkey()
    if direction == "r":
        goRight()
    elif direction == "l":
        goLeft()
RiveN
  • 2,595
  • 11
  • 13
  • 26
  • Or if you don't want to use `readchar` you can try something from here: https://stackoverflow.com/questions/3523174/raw-input-in-python-without-pressing-enter – RiveN Sep 27 '21 at 10:43
  • I get an error ModuleNotFoundError: No module named 'readchar', even after installing readchar with pip install readchar – laieman Sep 27 '21 at 10:48
  • Fixed the problem with python -m pip install readchar. It's working perfectly, thank you – laieman Sep 27 '21 at 10:54