I’m trying to create a simple signal handler for my Python application but the value of exiting does not change even when I use Ctrl-C. If I put exiting, out of the main function the value changes. How can I change the value of exiting when it is inside main()? Currently, the program always prints
False no matter if I press Ctrl-C or not.
import signal
import time
def main():
    exiting = False
    def handler(f, b):
        global exiting
        exiting = True
        return
    signal.signal(signal.SIGINT, handler)
    while True:
        print(exiting)
        time.sleep(1)
if __name__ == "__main__":
    main()
Advertisement
Answer
global should be included in the main function too.
import signal
import time
def main():
    global exiting
    exiting = False
    def handler(f, b):
        global exiting
        exiting = True
        return
    signal.signal(signal.SIGINT, handler)
    while True:
        print(exiting)
        time.sleep(1)
if __name__ == "__main__":
    main()
