[Python] Using sshkeyboard in Python

Discussão em 'Python' iniciado por Stack, Abril 12, 2025.

  1. Stack

    Stack Membro Participativo

    I want to use a Raspberry Pi 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.

    After a number of failed attempts, I posted a question here and Adel Alaa provide the following code, which works, but now I need to go further. His code successfully prints the six digit 'inputID' that was entered, and as it's a Global variable, I thought I could use it after that. As a test, I added the line: print(f"Entered ID: {inputID}") which I expected would print the final six digits to Terminal, but the code just stops. What do I need to do to use the Global variable in code after that point? I tried enclosing 'listen_keyboard(on_press = press) in a WHILE loop, hoping that after it ended the GLOBAL variable would be usable, but that didn't work either.

    while len(inputID) < 6: listen_keyboard(on_press = press)

    Thanks for any help!

    #! /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)

    added by me as a test


    print(f"Entered ID: {inputID}")

    Continue reading...

Compartilhe esta Página