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 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
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
Simple Keyboard Racing with Python Let's make a simple keyboard racing game using Python. In the game, the participant clicks a pair of keys in quick succession and the program shows the total time taken by the racer to cover the distance. Rules:Â As soon as you see 'GO!' on screen, start pressing the keys 'z' and 'x'. A '*' sign is s
2 min read
Running Python program in the background Let us see how to run a Python program or project in the background i.e. the program will start running from the moment device is on and stop at shut down or when you close it. Just run one time to assure the program is error-bug free One way is to use pythonw, pythonw is the concatenation of python
3 min read
How to test Typing Speed using Python? Prerequisites: Python GUI â tkinter In this article, we will create a program test the typing speed of the user with a basic GUI application using Python language. Here the Python libraries like Tkinter and Timeit are used for the GUI and Calculation of time for speed testing respectively. Â Also, th
3 min read
Measure The Time You Take To Type A Word Using Python Here, we have task to measure the time takes to type a word in Python. In this article we will see how to measure the time you to type a word in Python, we will type the word and measure the type using some simple generally used methods. Example : Input : Type the word 'GeeksforGeeks': GeeksforGeeks
3 min read