0

I want the loop to end if the forward slash key is pressed, but the script continues without stopping.

while kb.is_pressed('/') == False:
    for digit1 in range(startingDigit,10):
        for digit2 in range(0,10):
            for digit3 in range(0,10):
                for digit4 in range(0,10):
                    code = (str(digit1)+str(digit2)+str(digit3)+str(digit4))
                    print(code)
                    kb.write(code)
                    kb.send('enter')               #entering the code
                    time.sleep(0.5)
                    for i in range(0,5):           #removing the last attempt, ready to start again
                        kb.send('backspace')     
Angus87
  • 45
  • 4
  • Hey! Have you seen this post, a thorough discussion of detecting keyboard inputs https://stackoverflow.com/questions/13207678/whats-the-simplest-way-of-detecting-keyboard-input-in-python-from-the-terminal – the_good_pony Oct 17 '19 at 18:16

1 Answers1

3

kb.is_pressed only gets checked once per iteration of the while loop. All four of your digit-iterating for loops need to complete before it gets checked again. Since your for loops execute about 10,000 times before the while loop iterates once, and you've got a time.sleep(0.5) call, the kb.is_pressed call occurs no more than once every five thousand seconds.

Try putting the check inside the loops, so it occurs more often.

while True:
    for digit1 in range(startingDigit,10):
        for digit2 in range(0,10):
            for digit3 in range(0,10):
                for digit4 in range(0,10):
                    if kb.is_pressed('/'):
                        exit(0) #or `return`, if you're in a function; or raise an exception
                    code = (str(digit1)+str(digit2)+str(digit3)+str(digit4))
                    print(code)
                    kb.write(code)
                    kb.send('enter')               #entering the code
                    time.sleep(0.5)
                    for i in range(0,5):           #removing the last attempt, ready to start again
                        kb.send('backspace')    
Kevin
  • 74,910
  • 12
  • 133
  • 166