BEsmart
BEsmart

Reputation: 71

Pause keyboard listener temporarily for different keyboard input in python

I have a keyboard listener to check for some special keys, when pressed, to do some special stuff then.
When pressed '5' for example, the listener should pause, while a 'normal' keyboard input should be made, expecting a number.
My code below stops the listener and seems to take the input correctly (but with a horrible latency), but starting it again produces an 'Unhandled exception in listener callback'.
Any ideas or hints how this could be done and what about the strange latency of the 'normal' input? (Python 3.13.2 )

    from pynput.keyboard import Key, Listener

    def check_key(key):  # is called, when a key is pressed
        if hasattr(key, "char"):
            if key.char == "5":
                listener.stop() 
                repeat = True
                while repeat:
                    num = input("-> Number : ")  # horrible latency when typing
                    if num.isnumeric() and int(num):
                        repeat = False
                        number = int(num)
                listener.start()  # 'Unhandled exception in listener callback'
                print(number)
            

    # Non-Blocking Listener
    listener = Listener(on_press=check_key)
    listener.start()

Upvotes: 0

Views: 17

Answers (0)

Related Questions