How To Catch A Keyboardinterrupt in Python
Last Updated :
24 Sep, 2024
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.
Python
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.
Python
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.
Similar Reads
How To Resolve Issue " Threading Ignores Keyboardinterrupt Exception" In Python?
Threading is a powerful tool in Python for parallel execution, allowing developers to run multiple threads concurrently. However, when working with threads, there can be issues related to KeyboardInterrupt exceptions being ignored. The KeyboardInterrupt exception is commonly used to interrupt a runn
3 min read
How to Emulate a Do-while loop in Python?
We have given a list of strings and we need to emulate the list of strings using the Do-while loop and print the result. In this article, we will take a list of strings and then emulate it using a Do-while loop. Do while loop is a type of control looping statement that can run any statement until th
3 min read
How to Kill a While Loop with a Keystroke in Python?
While loops are used to repeatedly execute a block of code until a condition is met. But what if you want the user to stop the loop manually, say by pressing a key? Then you can do so by pressing a key. This article covers three simple ways to break a while loop using a keystroke:Using KeyboardInter
2 min read
Python program to check if a given string is Keyword or not
This article will explore how to check if a given string is a reserved keyword in Python. Using the keyword We can easily determine whether a string conflicts with Python's built-in syntax rules.Using iskeyword()The keyword module in Python provides a function iskeyword() to check if a string is a k
2 min read
How to clear screen in python?
When working in the Python interactive shell or terminal (not a console), the screen can quickly become cluttered with output. To keep things organized, you might want to clear the screen. In an interactive shell/terminal, we can simply usectrl+lBut, if we want to clear the screen while running a py
4 min read
How to make a Python program wait?
The goal is to make a Python program pause or wait for a specified amount of time during its execution. For example, you might want to print a message, but only after a 3-second delay. This delay could be useful in scenarios where you need to allow time for other processes or events to occur before
2 min read
How to Keep a Python Script Output Window Open?
We have the task of how to keep a Python script output window open in Python. This article will show some generally used methods of how to keep a Python script output window open in Python. Keeping a Python script output window open after execution is a common challenge, especially when running scri
2 min read
Disappearing Text Desktop Application in Python
In this article, we will build an exciting desktop application using Python and its GUI library, Tkinter. Disappearing Text Desktop Application in PythonThe app is simple to use. The user will start writing whatever he wants to write. If he takes a pause for 5 seconds, the text he has written is del
12 min read
How to Take a List as Input in Python Without Specifying Size?
In many situations, we might want to take list as input without knowing the size in Python beforehand. This approach provides flexibility by allowing users to input as many elements as they want until a specified condition (like pressing Enter) is met.Letâs start with the most simple method to take
2 min read
Check if a Key Exists in a Python Dictionary
Python dictionary can not contain duplicate keys, so it is very crucial to check if a key is already present in the dictionary. If you accidentally assign a duplicate key value, the new value will overwrite the old one.To check if given Key exists in dictionary, you can use either in operator or get
4 min read