I need to stop a program when a keyboard key q is pressed. How can I achieve that 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 pressing q after 3 seconds the program doesn't 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()
CodePudding user response:
time.sleep()
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.
CodePudding user response:
Instead of polling the keyboard to check if a certain key is pressed, you can just add a hotkey. When the hotkey q
(or whatever key you like) is pressed, a trigger function quit
is called.
import keyboard
import time
import sys
exitProgram = False
# prepare to exit the program
def quit():
global exitProgram
exitProgram=True
# set hotkey
keyboard.add_hotkey('q', lambda: quit())
# main loop to do things
while not exitProgram:
print("Hello")
time.sleep(1)
print("bye bye")
sys.exit()