I need to stop a program when a keyboard key q is pressed how can i achieve in the below code how can i ignore time.sleep & detect a keypress & exit the program by printing something , currently the keypress gets detected only after 10 seconds suppose i am preesing q after 3 seconds the program doesnt exit
import sys
import time
import keyboard
def hd():
print("Hi")
time.sleep(10)
if keyboard.is_pressed("q"):
print(keyboard.is_pressed("q"))
sys.exit()
while True:
hd()
>Solution :
time.wait is a blocking call. Nothing happens in your program while it runs.
Shorten the intervals. For example, instead of sleeping 10 seconds, sleep 100 × 0.1 second.
import sys
import time
import keyboard
def hd():
print("Hi")
for _ in range(100):
time.sleep(0.1)
if keyboard.is_pressed("q"):
print(keyboard.is_pressed("q"))
sys.exit()
while True:
hd()
For more complex behavior (doing actual work while also listening for a keyboard event) you will have to look into multithreading.