Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
How to use sys.argv in Python
Next article icon

How to capture SIGINT in Python?

Last Updated : 26 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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

# Python program to capture
# SIGINT in Python
  
# Import the libraries time, sys
import sys
from time import sleep
  
# Declare the variable with value 1
x = 1
  
# Construct an infinite while loop
while True:
  
    # Make a try-catch statement
    try:
  
        # Print the loop of numbers
        print(x)
  
        # Make Python sleep for some time
        # between print of each number
        sleep(.3)
  
        # Increase the loop by 1
        x += 1
  
    # Catch the exception of keyboard interruption
    except KeyboardInterrupt:
  
        # Print the statement for exception
        print("Loop is stopped")
  
        # Close the program
        sys.exit()
                      
                       

Output:

 



Next Article
How to use sys.argv in Python

V

vin8rai
Improve
Article Tags :
  • Python
  • Technical Scripter
  • Technical Scripter 2022
Practice Tags :
  • python

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 use sys.argv in Python
    In Python, sys.argv is used to handle command-line arguments passed to a script during execution. These arguments are stored in a list-like object, where the first element (sys.argv[0]) is the name of the script itself and the rest are arguments provided by the user. This feature is helpful when you
    3 min read
  • How to Exit a Python script?
    In this article, we are going to see How to Exit Python Script. Exiting a Python script refers to the termination of an active Python process. In this article, we will take a look at exiting a Python program, performing a task before exiting the program, and exiting the program while displaying a cu
    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
  • How to Get directory of Current Script in Python?
    A Parent directory is a directory above another file/directory in a hierarchical file system. Getting the Parent directory is essential in performing certain tasks related to filesystem management. In this article, we will take a look at methods used for obtaining the Parent directory of the current
    4 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
  • Convert integer to string in Python
    In this article, we’ll explore different methods for converting an integer to a string in Python. The most straightforward approach is using the str() function. Using str() Functionstr() function is the simplest and most commonly used method to convert an integer to a string. [GFGTABS] Python n = 42
    2 min read
  • How to Exit a Python Program in the Terminal
    Exiting a Python program might seem like a straightforward task, but there are several ways to do it depending on the context and requirements of your script. Whether you want to gracefully shut down your application or terminate it immediately, knowing the right approach can help you manage your co
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences