Search code examples
pythonpython-3.xpython-multithreading

How to check if a button is pressed while running a program in python


I want to run a program in Python while also checking the whole time whether or not a button (the physical type) has been pressed. The program looks something like this:

import stuff

a = True

def main():
        important stuff which takes about 10 seconds to complete

while True:
        if a == True:
                main() 
                #at the same time as running main(), I also want to check if a button
                #has been pressed. If so I want to set a to False

I can check if the button has been pressed after main is completed, but that would mean I would have to press the button at the split second when python checks if the button has been pressed (or hold down the button).

How can I make python check whether the button has been pressed while main() is running?


Solution

  • Here is something you can try. The main function is printing a number every second, and you can interrupt it by typing "s" + the Enter key :

    import threading
    import time
    
    a = True
    
    def main():
        for i in range(10):
            if a:
                time.sleep(1)
                print(i) 
    
    def interrupt():
        global a # otherwise you can only read, and not modify "a" value globally
        if input("You can type 's' to stop :") == "s":
            print("interrupt !")
            a = False
    
    
    t1 = threading.Thread(target=main)
    t1.start()
    interrupt()