Exit an endless loop Python program

This method uses an interrupt to capture keyboard CTRL+C entered on the command line, but then cleanly exits from the program’s main loop.

import signal
import time   #Only needed for the usage of sleep()

exit_program_interrupt_triggered = False

#*********************************************
#*********************************************
#********** KEYBOARD SIGINT HANDLER **********
#*********************************************
#*********************************************
def keyboard_signint_signal_handler(signal, frame):
    global exit_program_interrupt_triggered
    
    print("Keyboard SIGINT")
    exit_program_interrupt_triggered = True

signal.signal(signal.SIGINT, keyboard_signint_signal_handler)            #signal.SIGINT gives an interrupt when Ctrl+C or Ctrl+F2 is typed on the keyboard

#***********************************
#***********************************
#********** MAIN FUNCTION **********
#***********************************
#***********************************

    while True:                    #(Do forever)

        #<<<<<Do program stuff

        #----- CHECK FOR EXIT PROGRAM INTERRUPT OCCURED -----
        if exit_program_interrupt_triggered:
            print("Exiting main loop")
            break

        #Sleep to avoid cpu lockup
        time.sleep(0.01)   #Pause time in seconds

    #END OF while True:
    print("Shutting down")
Feel free to comment if you can add help to this page or point out issues and solutions you have found. I do not provide support on this site, if you need help with a problem head over to stack overflow.

Comments

Your email address will not be published. Required fields are marked *