detect key press in python?

lobuo picture lobuo · Jun 6, 2014 · Viewed 412.6k times · Source

I am making a stopwatch type program in python and I would like to know how to detect if a key is pressed (such as p for pause and s for stop), and I would not like it to be something like raw_input that waits for the user's input before continuing execution. Anyone know how to do this in a while loop?

Also, I would like to make this cross-platform, but if that is not possible, then my main development target is linux

Answer

user8167727 picture user8167727 · Jun 26, 2017

Python has a keyboard module with many features. Install it, perhaps with this command:

pip3 install keyboard

Then use it in code like:

import keyboard  # using module keyboard
while True:  # making a loop
    try:  # used try so that if user pressed other than the given key error will not be shown
        if keyboard.is_pressed('q'):  # if key 'q' is pressed 
            print('You Pressed A Key!')
            break  # finishing the loop
    except:
        break  # if user pressed a key other than the given key the loop will break