Search code examples
pythonpython-multithreading

Python script required multiple CTRL + C to stop


I have a scenario where I want to handle SIGINT int python to clean up some things and then exit. I am using the following code.

import threading
import signal

def shutdown_handler(*args):
    raise SystemExit('Exiting')

signal.signal(signal.SIGINT, shutdown_handler)

def main():
    while 1:
        time.sleep(2)
        print("***")
    
sub_thread = threading.Thread(target=main)
sub_thread.start()
sub_thread.join()

But it requires me to press CTRL + c multiple times before the program exits. The following works fine

import time
import threading
import signal

def shutdown_handler(*args):
    # Do some clean up here. 
    raise SystemExit('Exiting')

signal.signal(signal.SIGINT, shutdown_handler)

def main():
    while 1:
        time.sleep(2)
        print("***")
    
main()

I am using the first code, because of a suggestion on this thread
Can you please tell me why this behaviour. Is it because of multiple threads running and how can I get around this? Thanks


Solution

  • If terminating program with one Control-C is your only requirement, set daemon=True in constructor.

    import threading
    import signal
    
    def shutdown_handler(*args):
        raise SystemExit('Exiting')
    
    signal.signal(signal.SIGINT, shutdown_handler)
    
    def main():
        while 1:
            time.sleep(2)
            print("***")
        
    sub_thread = threading.Thread(target=main, daemon=True) # here
    sub_thread.start()
    sub_thread.join()