stuck on adding a timer to my keyboard press program

Question:

Im making a keyboard program that repeatedly presses a key every 0.1 seconds and uses esc as the hotkey to stop/start the program.

import keyboard
import time

keyboard.wait('esc')

name = ("python")

while name == "python":
keyboard.press_and_release('5')
time.sleep(0.1)

#this is where i want to add the timer

name = ("notpython")

I want to add the timer there so that after a few seconds the name variable changes from python to notpython and making the while loop false.

I’ve tried the time sleep function but it keeps printing 5 and doesnt stop.

Asked By: cxr

||

Answers:

maybe you can try something like this:

import keyboard
import time

keyboard.wait('esc')
name = ("python")
timer = time.time()

while name == "python":
    keyboard.press_and_release('5')
    time.sleep(0.1)

    timer2 = time.time()
    if timer2 - timer >= 5: name = "notpython"
Answered By: Berni
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.