2

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
Akaisteph7
  • 5,034
  • 2
  • 20
  • 43
Cai Allin
  • 307
  • 2
  • 11

1 Answers1

4

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() 
Akaisteph7
  • 5,034
  • 2
  • 20
  • 43
  • Thanks works perfectly! Thank you. I have another problem that has arisen, on the windows 7 machines the program will get input no matter which window is focused. However on windows 10 machines it does not get input when focused on a different window. Any ideas why? – Cai Allin Aug 01 '19 at 15:49
  • @CaiAllin From their [page](https://github.com/boppreh/keyboard#known-limitations) they say: "Other applications, such as some games, may register hooks that swallow all key events. In this case keyboard will be unable to report events.". I imagine then that this depends on the current open apps and how they handle key events. – Akaisteph7 Aug 01 '19 at 15:55
  • 1
    A bit of googling and it turns out UAC on windows 10 doesn't let you get the input without focus. The work around in my case was just to run with admin privileges. Another way would be to reduce UAC security, but I don't want to do that with the people who use the computers. – Cai Allin Aug 01 '19 at 16:02