Search code examples
python-3.xbluetoothkeyboardstdinsystemd

How to assign my wireless keyboard as stdin to a python3 script?


I have a wireless keyboard connected to a raspberry pi. Now when I start the Pi the keyboard will „hang“ at the login prompt.

The whole setup is headless and I want to assign the keyboard to a python3 script that is running at the same time through SystemD.

The stream is located at:

/dev/input/event0

As I said it’s fine if the script completely hijacks the keyboard.

Update

Another option for me would to simply start into my program at boot rather than the default shell prompt. This would ensure that it has the „focus“ of the keyboard.


Solution

  • Ok, i found a very simple answer : since you have python-evdev already installed on your system, you can use this module in your python3 program to achieve just what you want. Add import evdev to the top of your python3 program. Then, you have to create a evdev.device.InputDevice first thing in your program with "/dev/input/event0" as parameter (the path of your keyboard). Then, call evdev.device.InputDevice.grab, and it should be done ! I do not have the code of your program, but i wrote a little sample program:

    import evdev, sys
    
    if __name__ == "__main__":
        dev = evdev.device.InputDevice("/dev/input/event0")
        try:
            dev.grab()
        except IOError:
            print("error : /dev/input/event0 has already been grabbed")
            sys.exit(1)
        else:
            count = 0
            while count <= 100:
                instr = input("Enter something : ")
                print("You entered : " + instr)
                count += 1
            try:
                dev.ungrab() # important : free your keyboard when the script exits !
            except IOError:
                print("error : /dev/input/event0 has already been released")
                sys.exit(1)
    

    EDIT:

    I found out that the above sample program will not automatically capture the keystrokes and deliver you the text. You have to do that manually, an example can be found here