Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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. SIGINT is a signal sent when the user presses Ctrl+C (or Ctrl+F2 on Windows) to interrupt a running program.
When the signal module receives signals, it performs specific actions. It can capture the user's keyboard interruption through SIGINT and allow you to define custom behavior instead of just terminating the program.
Required Modules
The following modules are needed for signal handling in Python
Signal Module
The signal module provides mechanisms to handle asynchronous events. It comes builtin with Python, so no installation is required.
Sys Module
The sys module provides access to systemspecific parameters and functions. It's also builtin with Python.
Time Module
The time module enables working with timerelated functions. It comes preinstalled with Python.
Method 1: Using Signal Handlers
This approach uses signal.signal() to register a custom handler function ?
import signal
import sys
from time import sleep
# Define the signal handler function
def signal_handler(sig, frame):
print("\nSIGINT received! Cleaning up...")
print("Goodbye!")
sys.exit(0)
# Register the signal handler
signal.signal(signal.SIGINT, signal_handler)
print("Program is running. Press Ctrl+C to stop...")
# Simulate some work
count = 1
while True:
print(f"Working... {count}")
sleep(1)
count += 1
When you press Ctrl+C, the output will be ?
Program is running. Press Ctrl+C to stop... Working... 1 Working... 2 Working... 3 ^C SIGINT received! Cleaning up... Goodbye!
Method 2: Using Try-Except Blocks
This approach catches KeyboardInterrupt exception directly ?
import sys
from time import sleep
count = 1
try:
print("Program started. Press Ctrl+C to interrupt...")
while True:
print(f"Count: {count}")
sleep(0.5)
count += 1
except KeyboardInterrupt:
print("\nKeyboard interrupt received!")
print("Program terminated gracefully.")
sys.exit(0)
The output shows graceful termination ?
Program started. Press Ctrl+C to interrupt... Count: 1 Count: 2 Count: 3 Count: 4 ^C Keyboard interrupt received! Program terminated gracefully.
Method 3: Custom Cleanup Actions
This example shows how to perform cleanup operations before exiting ?
import signal
import sys
from time import sleep
class DataProcessor:
def __init__(self):
self.data = []
self.running = True
def cleanup(self):
print(f"\nSaving {len(self.data)} items...")
print("Cleanup completed!")
def signal_handler(self, sig, frame):
print("\nReceived interrupt signal")
self.running = False
self.cleanup()
sys.exit(0)
def run(self):
# Register signal handler
signal.signal(signal.SIGINT, self.signal_handler)
count = 1
while self.running:
self.data.append(f"item_{count}")
print(f"Processing item {count}")
sleep(1)
count += 1
# Create and run processor
processor = DataProcessor()
processor.run()
Processing item 1 Processing item 2 Processing item 3 ^C Received interrupt signal Saving 3 items... Cleanup completed!
Comparison
| Method | Best For | Advantages |
|---|---|---|
| Signal Handler | Systemlevel control | More control, handles other signals |
| TryExcept | Simple applications | Pythonic, easy to understand |
| Classbased | Complex applications | Objectoriented, reusable |
Key Points
-
signal.SIGINTcorresponds to Ctrl+C interruption -
KeyboardInterruptexception is raised when SIGINT occurs - Always perform cleanup operations before exiting
- Use
sys.exit()for clean program termination
Conclusion
Capturing SIGINT in Python allows graceful program termination and cleanup operations. Use signal handlers for systemlevel control or tryexcept blocks for simple interrupt handling. Both approaches ensure your program exits cleanly when interrupted.
