How To Catch A Keyboardinterrupt in Python
In Python, KeyboardInterrupt is a built-in exception that occurs when the user interrupts the execution of a program using a keyboard action, typically by pressing Ctrl+C. Handling KeyboardInterrupt is crucial, especially in scenarios where a program involves time-consuming operations or user interactions. In this article, we'll explore how to catch KeyboardInterrupt in Python.
Syntax
To catch a KeyboardInterrupt in Python, you can use a try-except block. The KeyboardInterrupt exception is raised when the user presses Ctrl+C, and you can handle it gracefully by incorporating the following syntax:
try:
# Code that may raise KeyboardInterrupt
except KeyboardInterrupt:
# Code to handle the KeyboardInterrupt
How to Catch A Keyboardinterrupt in Python?
Below, is an example that shows How To Catch A Keyboardinterrupt In Python.
Example 1: Basic KeyboardInterrupt Handling
Let's consider a simple example where a program waits for user input, and we want to catch KeyboardInterrupt to exit the program gracefully:
In this example, the program continuously prompts the user for input. If the user interrupts the program with Ctrl+C, the KeyboardInterrupt exception is caught, and a message is displayed, gracefully terminating the program.
try:
while True:
user_input = input("Enter something (Ctrl+C to exit): ")
print(f"You entered: {user_input}")
except KeyboardInterrupt:
print("\nProgram terminated by user.")
try:
while True:
user_input = input("Enter something (Ctrl+C to exit): ")
print(f"You entered: {user_input}")
except KeyboardInterrupt:
print("\nProgram terminated by user.")
Output
Enter something (Ctrl+C to exit): GeeksforGeeks
You entered: GeeksforGeeks
Program terminated by user.
Example 2: Handling KeyboardInterrupt in a Long-Running Process
In some cases, you may have a long-running process where you want to catch KeyboardInterrupt and perform cleanup operations before exiting. Consider the following example:
In this example, the long_running_process
function simulates a process that takes some time to complete. If the user interrupts the process with Ctrl+C, the KeyboardInterrupt exception is caught, and a cleanup message is displayed before exiting.
import time
def long_running_process():
try:
print("Performing a long-running process. Press Ctrl+C to interrupt.")
for i in range(10):
time.sleep(1)
print(f"Processing step {i + 1}")
except KeyboardInterrupt:
print("\nInterrupted! Cleaning up before exiting.")
# Perform cleanup operations here if needed
finally:
print("Exiting the program.")
# Call the long_running_process function
long_running_process()
import time
def long_running_process():
try:
print("Performing a long-running process. Press Ctrl+C to interrupt.")
for i in range(10):
time.sleep(1)
print(f"Processing step {i + 1}")
except KeyboardInterrupt:
print("\nInterrupted! Cleaning up before exiting.")
# Perform cleanup operations here if needed
finally:
print("Exiting the program.")
# Call the long_running_process function
long_running_process()
Output
Performing a long-running process. Press Ctrl+C to interrupt.
Processing step 1
Processing step 2
Processing step 3
Processing step 4
Processing step 5
Exiting the program.
Conclusion
Catching KeyboardInterrupt in Python is essential for handling user interruptions gracefully, especially in programs with time-consuming operations. By using a try-except block, you can effectively catch and handle KeyboardInterrupt, ensuring that your programs exit in a controlled manner. The provided examples illustrate how to implement KeyboardInterrupt handling in both basic user input scenarios and long-running processes.