Search code examples
pythontimebotssleep

how to stop python program when time.sleep() is in progressing


i made a bot that control my mouse and my keyboard to make the games im playing easier but somehow i can't stop that program easily... i made a loop with condition when i press enter the program will be stopped but the time.sleep() progressing dnt allow that happening, however i can't make an integer condition because i want my program unstoppable i mean it must stop when i press a key on my keyboard for example:

import keyboard
import time

while True:
    print('hello world')
    time.sleep(3)
    if keyboard.is_pressed('enter'):
        break

i know that i can hold 'enter' button for 3 secs but my real program has time.sleep() duration bigger than 1 min that i can't hold enter all that time, is there any other code like time.sleep() i can use to solve my problem ?


Solution

  • Instead of a 3-second sleep how about 30 short 0.1-second naps? Food for thought.

    import keyboard
    import time
    
    enter_pressed = 0
    while True:
        print('hello world')
        time.sleep(0.1)
        if keyboard.is_pressed('enter'):
            enter_pressed += 1
        else:
            enter_pressed = 0
    
        if enter_pressed >= 10:
            break # enter pressed for 1 sec