How to capture SIGINT in Python?

In this article, we will learn how to capture SIGINT in Python and what has to be done after capturing it.

When the signal module receives signals, it does a certain action. Besides that, it can capture the user's interruption through the keyboard using SIGINT.

Modules Needed

Signal Module

The term "signal" refers to the process by which a program can receive information from the operating system. Additionally, the signals are sent to the program when the operating system detects specific events. By executing the following command at the terminal, the signal module can be installed −

pip install signal

Sys Module

The sys module in Python is what offers several functions and variables to alter different parts of the Python run environment. The sys module can be installed with the command −

pip install os-sys

Time Module

Python's time module, enables users to work with time and record information regarding time. The time module typically comes preinstalled with Python, so there is no need to install it; but, if it didn't, you can use the command below to install it −

pip install python-time

Now we will go through the implementation of capturing SIGINT in python step-by-step.

Step-by-step Implementation

Step 1: Importing Libraries

Firstly, we must import all the required libraries using the import keyword. The signal, sys, and sleep libraries are among them.

# importing signal and sys modules 
import signal
import sys
# importing sleep function from the time module
from time import sleep

Step 2: Creating a Function

We now create a function that, in the event of a keyboard interruption, it will be called by accepting any two arguments. In this case, the arguments have been taken as sig and frame.

# creating a function that accepts the two arguments 
# it is called when the user makes a keyboard interruption
def signalHandling(signal, frame):

Step 3: Defining Custom Handlers

Here we use the signal.signal() function to define custom handlers that must be called when a signal is received. Additionally, we define signal.SIGINT, which causes interruption by typing Ctrl+C or Ctrl+F2 on the keyboard.

signal.signal(signal.SIGINT, signalHandling)

Step 4: Printing Random Message

Next, print any random message with a few lines to let the user know what to do if the keyboard is interrupted.

# printing random message
print(' printing random messages')

Step 5: Set Sleep Time

Lastly, set Python sleep time for some random number of seconds.

# sleep time 
sleep(time in sec)


The program has a catch: If you are running it on Windows, you can stop it and capture SIGINT by pressing Ctrl and F2, but if you are running it on Linux, you can stop it by pressing Ctrl and C at the same time.

Capturing SIGINT in Python

Algorithm (Steps)

Following are the Algorithms/steps to be followed to perform the desired task. −

  • Use the import keyword to import the signal and sys modules.

  • Use the import keyword to import the sleep function from the time module.

  • Create a variable and initialize its value with 1(It is used to represent the number of times the loop is executed).

  • Use the while True, to loop an infinite number of times.

  • Use try-except blocks for handling errors/exceptions.

  • Printing the count of the number of times the loop is executed by printing the above variable.

  • Use the sleep() function to sleep for a random number of seconds time between printing of each number by passing the number as an argument to it.

  • Increment the loop execution count value by 1.

  • Use the except block for handling the keyboard interruption exception.

  • Print any message if a keyboard interruption exception occurs.

  • Use the exit() function of the sys module to close/exit the program.


The following program to capture the SIGINT using try/catch exceptions −

# importing signal and sys modules
import signal
import sys
# importing sleep function from the time module
from time import sleep
# initializing variable with value 1 to count the number of times the loop is executed
k = 1
# looping infinite times using a while loop
while True:
   # using try-except blocks for handling errors/exceptions
      # Printing the count of the number of times the loop is executed
      #sleeping for a random number of seconds time between printing of a number
      # Incrementing the loop execution count by 1
      k += 1
   # Handling the keyboard interruption exception using except block
   except KeyboardInterrupt:
      # printing any message if keyboard interruption exception occurs
      print("The loop has stopped!!")
      # closing/exiting the program


On execution, the above program will generate the following output −

The loop has stopped!!

In this program, we use a try-catch statement to handle keyboard exceptions. While running an increasing loop of numbers in the try block, we caught the keyboard interruption in the catch block.


In this article, we learned how to use Python to capture SIGINT. We learned how to use try/catch statements to achieve the same. Try and catch statements can be used to handle exceptions like divide by 0 and keyboard interruption etc.