Detecting keyboard input in Python

At our last Hull Raspberry Jam, one of our budding Python coders asked me how she could detect keyboard input in a Python script and perform different actions dependent upon which key was pressed.

We both did a bit of searching around and found a few sample pieces of code, but none of them quite did what we wanted. As we were leaving I said that I would research it a bit more, and if she had not found out how to do it before the next Hull Raspberry Jam, I would have some working code for her to use.

I don’t want to ruin the surprise about what her plan is, but needless to say, it will be a very cool project if she completes what she wants to do, more on that later!

I was rather fortunate in that Michael Horne send some sample code around about how to remote control CamJam’s fabulous Robot Kit including a piece of code that would allow you to control a robot with a bluetooth keyboard or the like. Now this was doubly of interest to me, as I also have a team from my school entering the PiWars robot challenge, but that’s for another post!

So using that code as my starting point, here is a fairly simple bit of Python that will react to keyboard presses.


# adapted from

import sys, termios, tty, os, time

def getch():
    fd = sys.stdin.fileno()
    old_settings = termios.tcgetattr(fd)
        ch =

        termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
    return ch

button_delay = 0.2

while True:
	char = getch()

	if (char == "p"):

	if (char == "a"):
		print("Left pressed")

	elif (char == "d"):
		print("Right pressed")

	elif (char == "w"):
		print("Up pressed")

	elif (char == "s"):
		print("Down pressed")

	elif (char == "1"):
		print("Number 1 pressed")

It should be quite easy to adjust this for whichever keyboard presses you need to detect and then add in the functions you want to trigger from each key press!

Happy hacking!

Leave a Reply

Your email address will not be published. Required fields are marked *