How To Catch A Keyboardinterrupt in Python
In PythonKeyboardInterrupt is a built-in exception that occurs when the user interrupts the execution of a program using a keyboard actiontypically by pressing Ctrl+C. Handling KeyboardInterrupt is crucialespecially in scenarios where a program involves time-consuming operations or user interactions. In this articlewe'll explore how to catch KeyboardInterrupt in Python.
Syntax
To catch a KeyboardInterrupt in Pythonyou can use a try-except block. The KeyboardInterrupt exception is raised when the user presses Ctrl+Cand 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?
Belowis 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 inputand we want to catch KeyboardInterrupt to exit the program gracefully:
In this examplethe program continuously prompts the user for input. If the user interrupts the program with Ctrl+Cthe KeyboardInterrupt exception is caughtand a message is displayedgracefully 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.")
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 casesyou may have a long-running process where you want to catch KeyboardInterrupt and perform cleanup operations before exiting. Consider the following example:
In this examplethe long_running_process function simulates a process that takes some time to complete. If the user interrupts the process with Ctrl+Cthe KeyboardInterrupt exception is caughtand 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()
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 gracefullyespecially in programs with time-consuming operations. By using a try-except blockyou can effectively catch and handle KeyboardInterruptensuring 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.