Why is my code looping twice when using keyboard?

998 Views Asked by At

I am writing code to alert the user when a specific string of numbers is entered. The code runs seems to run as intended but outputs "1122334455" when it should give me "12345":

import sys
sys.path.append('..')
import keyboard

line = ''
ISBN10 = ''
number = ""

def print_pressed_keys(e):
    global line, ISBN10, number
    line = line.join(str(code) for code in keyboard._pressed_events)
    if line == "2":
        number = 1
    elif line == "3":
        number = 2
    elif line == "4":
        number = 3
    elif line == "5":
        number = 4
    elif line == "6":
        number = 5
    elif line == "7":
        number = 6
    elif line == "8":
        number = 7
    elif line == "9":
        number = 8
    elif line == "10":
        number = 9
    elif line == "11":
        number = 0
    ISBN10 = ISBN10 + str(number)
    if len(ISBN10) > 10:
        ISBN10 = ISBN10[1:11]
    print("ISBN10: " + ISBN10)

keyboard.hook(print_pressed_keys)
keyboard.wait()

The output is:

ISBN10: 1
ISBN10: 11
ISBN10: 112
ISBN10: 1122
ISBN10: 11223
ISBN10: 112233

Whereas it should be:

ISBN10: 1
ISBN10: 12
ISBN10: 123
1

There are 1 best solutions below

3
On BEST ANSWER

This is because keyboard.hook() will run its callback when you press a key and when you release it. Therefore, twice for every key press. You need to have it run just when a key is pressed:

keyboard.on_press(print_pressed_keys)
# Added hotkey so you can exit block and continue program execution
keyboard.wait("ESC") 
# Run this after you press escape so it stops running the hook when you exit
keyboard.unhook_all()