John Sullivan
John Sullivan

Reputation: 13

Using sshkeyboard in Python to return a variable

I want to use a Raspberry Pi 5 running Python3 to read the keypresses on a USB connected keypad. I am using sshkeyboard and have read the questions and answers here on that topic, but they only detail printing the key to Terminal. I need to return the key that was pressed as a variable to use in the code that will follow.

Persons using the keypad will enter their 6-digit ID. The code will run in a while loop until 6 key presses have been entered and concatenated into a string named 'inputID'. The string can then be used in later code to validate the user against a database.

sshkeyboard reads the key pressed and displays it in Terminal but I have not yet been able to capture the 'key' in order to add it to the string. It seems to go out-of-scope before I can capture it.

I have reduced the normal example code provided in the sshkeyboard tutorial to only display the single key press character in Terminal, which works as expected. I cannot however collect six key presses and display them as one 6 character string.

Any help will be appreciated. The code I've tried is as follows:

#! /usr/bin/python3

# import listen_keyboard from the library
from sshkeyboard import listen_keyboard

# create an empty string named inputID
inputID = ""

# define a function that uses a 'key' provided by listen_keyboard, 
# prints 'key' to the Terminal and returns 'key' 
def press(key):
    print(key)
    return key
    
# run press(key) in a while loop and concatenate
# the result to inputID until the length of
# inputID is 6 characters   
while (len(inputID) < 6):
    
    listen_keyboard(
        on_press = press
        
    )
    inputID = inputID + key
    
# print the string of 6 characters to the Terminal window
print('inputID is: ', inputID)




    
    

Upvotes: 1

Views: 15

Answers (1)

Adel Alaa
Adel Alaa

Reputation: 185

listen_keyboard is blocking and does not return the key directly to your loop.

Fixed Code

#! /usr/bin/python3

from sshkeyboard import listen_keyboard

# Global variable to store the input ID
inputID = ""

# Function to capture key presses
def press(key):
    global inputID
    if len(inputID) < 6:
        inputID += key
        print(f"Current input: {inputID}")

    # Stop listening once we reach 6 characters
    if len(inputID) == 6:
        print(f"Final inputID: {inputID}")
        return False  # This stops `listen_keyboard`

# Start listening
listen_keyboard(on_press=press)

Upvotes: 1

Related Questions