Archive

Posts Tagged ‘SIGINT’

Handle CTRL+C in your script

November 21, 2012 Leave a comment

Question

In your script you want to handle the SIGINT signal, i.e. when the user wants to stop the script with CTRL+C, you want to call a function to handle the situation.

Answer

Here is an example:

#!/usr/bin/env python

import signal
import time

def sigint_handler(signum, frame):
    print 'Stop pressing the CTRL+C!'

signal.signal(signal.SIGINT, sigint_handler)

def main():
    while True:
       print '.'
       time.sleep(1)

##########

if __name__ == "__main__":
    main()

Now the script is immune against CTRL+C. You will have to kill it (“kill <PID>”) if you want to stop it.

If you want protection against “kill <PID>”, handle the SIGTERM signal too :)

Design a site like this with WordPress.com
Get started