How to Create a Custom KeyboardInterrupt in Python
In Python, custom KeyboardInterrupts means handling the interruption signals like Ctrl+C in a customized way. Instead of the default behavior, you can define specific actions to be executed when the interrupt signal is received. In this article, we will learn to Create a Custom KeyboardInterrupt in Python using two different approaches.
Create a Custom KeyboardInterrupt
Below are the possible approaches to Creating a Custom KeyboardInterrupt in Python.
- Using a Custom Exception Handler
- Using a Signal Handler
Create a Custom KeyboardInterrupt Using a Custom Exception Handler
In this example, we are using a custom exception handler to manage the KeyboardInterrupt exception. When Ctrl+C is pressed, the KeyboardInterrupt is caught, triggering the custom_keyboard_interrupt_handler function to execute custom cleanup actions.
import time
def custom_keyboard_interrupt_handler():
print("Custom KeyboardInterrupt caught! Cleaning up...")
try:
print("Press Ctrl+C to interrupt")
while True:
time.sleep(1)
except KeyboardInterrupt:
custom_keyboard_interrupt_handler()
print("Program terminated.")
Output:

Create a Custom KeyboardInterrupt Using a Signal Handler
In this approach, we are using the signal module to catch the SIGINT signal, which is triggered by pressing Ctrl+C. We define a custom handler function, custom_keyboard_interrupt_handler, and register it to handle the SIGINT signal. When Ctrl+C is pressed, the custom handler is executed, printing a custom message.
import signal
import time
def custom_keyboard_interrupt_handler(signum, frame):
print("Custom KeyboardInterrupt (Ctrl+C) caught! Cleaning up...")
# Register the custom signal handler for SIGINT (Ctrl+C)
signal.signal(signal.SIGINT, custom_keyboard_interrupt_handler)
try:
print("Press Ctrl+C to interrupt")
while True:
time.sleep(1)
except KeyboardInterrupt:
print("Standard KeyboardInterrupt caught! Exiting...")
print("Program terminated.")
Output:
