Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Polling the keyboard (detect a keypress) in python

How can I poll the keyboard from a console python app? Specifically, I would like to do something akin to this in the midst of a lot of other I/O activities (socket selects, serial port access, etc.):

while True:     # doing amazing pythonic embedded stuff     # ...      # periodically do a non-blocking check to see if     # we are being told to do something else     x = keyboard.read(1000, timeout = 0)      if len(x):         # ok, some key got pressed         # do something 

What is the correct pythonic way to do this on Windows? Also, portability to Linux wouldn't be bad, though it's not required.

like image 555
K. Brafford Avatar asked Nov 15 '08 03:11

K. Brafford


People also ask

How does Python detect pressed keyboard?

To detect keypress, we will use the is_pressed() function defined in the keyboard module. The is_pressed() takes a character as input and returns True if the key with the same character is pressed on the keyboard.

How do I capture a keyboard input in Python?

Use the input() function to get Python user input from keyboard. Press the enter key after entering the value. The program waits for user input indefinetly, there is no timeout. The input function returns a string, that you can store in a variable.

How can I tell if a key is pressed on my keyboard?

Visit Keyboard Checker and tap the key you want to test. If a key on the on-screen keyboard turns green, that means the keypress is being recognized however, the keyboard you see is NOT going to be an accurate representation of the keyboard you're using.

How do you wait for key press in Python?

In Python 2 use raw_input(): raw_input("Press Enter to continue...") This only waits for the user to press enter though. This should wait for a keypress.


1 Answers

The standard approach is to use the select module.

However, this doesn't work on Windows. For that, you can use the msvcrt module's keyboard polling.

Often, this is done with multiple threads -- one per device being "watched" plus the background processes that might need to be interrupted by the device.

like image 118
S.Lott Avatar answered Sep 21 '22 16:09

S.Lott