pythonpython-keyboard

Looping until a specific key is pressed


I was trying to make a while loop which would stop running when a specific key is pressed. The problem is that the loop runs infinitely. My loop:

import time
import keyboard

while (not keyboard.is_pressed("esc")):
    print("in loop...")
    time.sleep(2)

I am using the keyboard module. What is wrong with my loop and how can I fix it? (I don't really want to use a Repeat-until or equivalent loop in Python thing in this case.)


Solution

  • Here is a solution which works:

    import keyboard
    import time
    import threading
    
    class main:
        def __init__(self):
            # Create a run variable
            self.run = True
    
            # Start main thread and the break thread
            self.mainThread = threading.Thread(target=self.main)
            self.breakThread = threading.Thread(target=self.breakThread)
    
            self.mainThread.start()
            self.breakThread.start()
    
        def breakThread(self):
            print('Break thread runs')
            # Check if run = True
            while True and self.run == True:
                if keyboard.is_pressed('esc'):
                    self.newFunction()
    
        def main(self):
            print('Main thread runs')
            
            # Also check if run = True   
            while not keyboard.is_pressed('esc') and self.run:
                print('test')
                time.sleep(2)
                
                # Break like this
                if keyboard.is_pressed('esc'):
                    break
    
                print('test')
                time.sleep(2)
    
        def newFunction(self):
            self.run = False
            print('You are in the new function!')
    
    program = main()