Home > operating systems, python > Handle CTRL+C in your script

Handle CTRL+C in your script


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.


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 '.'


if __name__ == "__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 :)

  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: