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 CodeSpeedy.py
b'p'
b'8'
b'6'
b'1'
b'/'
b']

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.

Learn,

2 responses to “How to detect which key is pressed in Python – Keypress detection in Python”

  1. SJ7 says:

    doesnt work, is this not python 3.0?

    • Saruque Ahamed Mollick says:

      I have tested it with Python 3.6
      Can you let us know which kind of error you are getting so that we can help you out

Leave a Reply

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