How to capture SIGINT in Python?
Last Updated :
26 Apr, 2025
The signal module performs a specific action on receiving signals. Even it has the ability to capture the interruption performed by the user through the keyboard by use of SIGINT. This article will discuss SIGINT only, how to capture it, and what to do after it has been captured.
Modules Required:
Signal: The technique through which a program can receive information from the operating system is known as a signal. Further, the signals are passed to the program when the operating system has received certain events. The signal module can be downloaded by running the following command in the terminal:
pip install signals
Sys: The Python sys module that provides various functions and variables to manipulate various parts of the Python run environment is called the sys module. You can download the sys module through the following command:
pip install os-sys
Time: The time module in Python which allows the user to work with time and capture details related to time is known as the Python module. The time module usually comes preinstalled with Python, so there is no need to install it, but in case, it hasn’t come preinstalled with your Python, then you can use the following command:
pip install python-time
Stepwise Implementation:
Step 1: First of all, we need to import some libraries of Python. These libraries include signal, sys, and sleep.
Python3
import signal
import sys
from time import sleep
|
Step 2: Now, we create a function to be called with any two arguments when a keyboard interruption is made. Here, we have taken the arguments as sig and frame.
Python3
def signal_handler(sig, frame):
|
Step 3: In this step, we define custom handlers that need to be executed on receiving a signal using the signal.signal() function. Also, we define signal.SIGINT, which will perform interruption through the keyboard either by pressing Ctrl+ C or Ctrl+F2.
Python3
signal.signal(signal.SIGINT, signal_handler)
|
Step 4: Later on, display some lines as a message to make the user know what to do for keyboard interruption.
Python3
print ( '#Lines to display' )
|
Step 5: Finally, make Python sleep for some time.
Python3
sleep(Time duration in seconds)
|
Note: The catch in the program is that if you running this program on Windows, then you can stop the program, i.e., capture SIGINT by pressing Ctrl and F2 simultaneously while if you are running this program on Linux, then you can stop the program by pressing Ctrl and C simultaneously.
How to capture SIGINT in Python
In this program, we capture keyboard exceptions using a try-catch statement. In the try block, we had run an increasing loop of numbers, while in the catch block, we captured the keyboard interruption.
Python
import sys
from time import sleep
x = 1
while True :
try :
print (x)
sleep(. 3 )
x + = 1
except KeyboardInterrupt:
print ( "Loop is stopped" )
sys.exit()
|
Output:

Similar Reads
How to Capture udp Packets in Python
Capturing UDP (User Datagram Protocol) packets is a fundamental skill for network programmers and security enthusiasts. Python, being a versatile and powerful programming language, offers various libraries and tools to facilitate packet capture. In this article, we'll explore how to capture UDP pack
3 min read
How to Index and Slice Strings in Python?
In Python, indexing and slicing are techniques used to access specific characters or parts of a string. Indexing means referring to an element of an iterable by its position whereas slicing is a feature that enables accessing parts of the sequence. Table of Content Indexing Strings in PythonAccessin
2 min read
How to Measure Elapsed Time in Python
In Python, we can measure the elapsed time (time taken for a specific task to complete) on executing a code segment or a Python script. It's useful when we are benchmarking the code, debugging or optimizing performance. Python provides several built-in modules to measure the execution time of code b
4 min read
How to capture a image from webcam in Python?
In this article, we will discuss how to capture an image from the webcam using Python. We will use OpenCV and PyGame libraries. Both libraries include various methods and functions to capture an image and video also. By using, these vast libraries we need to write only 4 to 5 lines of code to captur
3 min read
C strings conversion to Python
For C strings represented as a pair char *, int, it is to decide whether or not - the string presented as a raw byte string or as a Unicode string. Byte objects can be built using Py_BuildValue() as // Pointer to C string data char *s; // Length of data int len; // Make a bytes object PyObject *obj
2 min read
How to Call a C function in Python
Have you ever came across the situation where you have to call C function using python? This article is going to help you on a very basic level and if you have not come across any situation like this, you enjoy knowing how it is possible.First, let's write one simple function using C and generate a
2 min read
How to Print Exception Stack Trace in Python
In Python, when an exception occurs, a stack trace provides details about the error, including the function call sequence, exact line and exception type. This helps in debugging and identifying issues quickly. Key Elements of a Stack Trace:Traceback of the most recent callLocation in the programLine
3 min read
How to log a Python exception?
To log an exception in Python we can use a logging module and through that, we can log the error. The logging module provides a set of functions for simple logging and the following purposes DEBUGINFOWARNINGERRORCRITICALLog a Python Exception Examples Example 1:Logging an exception in Python with an
2 min read
Python | Add Logging to a Python Script
In this article, we will learn how to have scripts and simple programs to write diagnostic information to log files. Code #1 : Using the logging module to add logging to a simple program import logging def main(): # Configure the logging system logging.basicConfig(filename ='app.log', level = loggin
2 min read
Detect script exit in Python
Python is a scripting language. This means that a Python code is executed line by line with the help of a Python interpreter. When a python interpreter encounters an end-of-file character, it is unable to retrieve any data from the script. This EOF(end-of-file) character is the same as the EOF that
2 min read