How to detect which key is pressed in Python – Keypress detection in Python

This tutorial is on key press detection in Python. Today we are going to learn how to detect key press in Python. I am not talking about only the detection of a key press, we will also learn how to detect which key is pressed in Python.

Detect which key is pressed in Python

Here we are going to provide a Python program to detect which key is pressed. The program will work as below:

  • After running the program, you can press any key.
  • In the terminal, the program will tell you which key is pressed using the keyboard.

Python Program to detect key press:

import msvcrt
while True:
    if msvcrt.kbhit():
        key_stroke = msvcrt.getch()
        print(key_stroke)   # will print which key is pressed

Here is the Python Code.

The sample output is:

$ python

Screenshot of the output:

detect which key is pressed in Python

Output: detect which key is pressed in Python

After the small b, in between the single quotes, the pressed key is shown.

Here you can see that we are using msvcrt module which is a module of windows. Though I am not sure if it will work on Linux or not. It has been tested on Windows and it works fine for me.


There are other ways too to detect keypress in Python. But I personally like this one.

Feel free to let us know if you find a better way to do this in the below comment section.


Leave a Reply

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