Best way to detect keypress with Python?[SOLVED]


#1

I would like to control my BrickPi robot with the keyboard, but I don’t want to use raw_input that requires the user to press enter. What is a good way to detect keypresses? I tried using curses, but when I run the code, I get a message saying curses.cbreak() returned an error. I did a little looking online and it seems this problem is due to trying to use this with IDLE. It seems like I could also use pygame to detect keypresses, but I haven’t worked much on that yet. Any recommendations?


#2

Hi HPNed :slight_smile:
You might want to try the readchar module (pip install readchar).


#3

@spacefox.brick: that package looks pretty good for capturing the input without pressing ENTER. Thanks for sharing.


#4

Great question, I have wanted to do that myself, and found the python library curses great. https://docs.python.org/3.5/library/curses.html It is preinstalled onto any computer with python, and is a very capable library.
Also check out the robotic arm example by Dexter Industries, [https://github.com/DexterInd/BrickPi_Python/blob/master/Project_Examples/Robotic_Arm.py] It uses the curses library for controllig it through arrow keys.(https://github.com/DexterInd/BrickPi_Python/blob/master/Project_Examples/Robotic_Arm.py)

And for a important piece of advice, make sure you have curses exit properly, if you do not exit properly your keyboard on that terminal window will be useless.
Having some error handling would also be good in-case of a bug causing your program to exit improperly.
If something does go wrong, simply do CTRL-C to exit the python program, and CTRL-D to logout off ssh if your using ssh. If you are not using ssh just open a new terminal widow.

Have fun!


#5