Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to stop a function & exit program running in a while loop on key press?

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading