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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With