Python KeyboardInterrupt – Tutorial with Examples

Python KeyboardInterrupt - Tutorial with Examples

Python is a programming language that is easy to learn and use. It is widely used for web development, artificial intelligence, data analysis, and a range of other applications. However, like any other programming language, it is also prone to errors and issues.

The “KeyboardInterrupt” error is one of the most common issues Python developers face. This error is triggered when the user presses the Ctrl+C combination or the “break” key on the keyboard while a Python program is executing.

This tutorial will explain how the KeyboardInterrupt exception works in Python and how to handle it using various examples.

What is KeyboardInterrupt in Python?

The KeyboardInterrupt exception is an error that is triggered when the user interrupts a running Python program. The exception is raised by the interpreter when the user presses the Ctrl+C combination or the “break” key on the keyboard.

How to Handle KeyboardInterrupt Exception in Python?

There are several ways to handle the KeyboardInterrupt exception in Python. The methods include:

  • Using try-except blocks.
  • Using the signal module.
  • Using the threading module.

The following code snipeet will show you how to handle the ‘KeyboardInterrupt’ exception with the help of try and except blocks:

import time

try:
    while True:
        print('Hello, World!')
        time.sleep(1)
except KeyboardInterrupt:
    print('Goodbye, World!')

Output

Hello, World!
Hello, World!
Hello, World!
Goodbye, World!

In this example, a while loop runs continuously and prints “Hello, World!” every second. However, when the user presses the Ctrl+C combination or the “break” key, the KeyboardInterrupt exception is raised, and the program exits gracefully by printing “Goodbye, World!”.

Using the Signal Module

The signal module can be used to handle the KeyboardInterrupt exception in Python. The signal module provides a cross-platform way of handling signals, including the SIGINT signals that are triggered by the Ctrl+C combination on Unix-based systems.

The following code snippet will show you how to handle the ‘KeyboardInterrupt’ exception with the help of the signal module:

import signal
import time

def handle_signal(signal_number, frame):
    print('Goodbye, World!')
    exit(0)

signal.signal(signal.SIGINT, handle_signal)

while True:
    print('Hello, World!')
    time.sleep(1)

Output

Hello, World!
Hello, World!
Hello, World!
Goodbye, World!

In this example, a while loop runs continuously and prints “Hello, World!” every second. However, when the user presses the Ctrl+C combination or the “break” key, the handle_signal() function is called, and the program exits gracefully by printing “Goodbye, World!”.

Using the Threading Module

The threading module can be used to handle the KeyboardInterrupt exception in Python. The threading module allows you to create lightweight processes, known as threads, that run in parallel with the main program. In this way, the threads can provide a mechanism for handling the KeyboardInterrupt exception without disrupting the main program.

The following code snippet will show you how to handle the ‘KeyboardInterrupt’ exception with the help of the threading module:

import threading
import time

def check_keyboard_interrupt():
    while True:
        if threading.current_thread().stopped:
            print('Goodbye, World!')
            exit(0)
        time.sleep(1)

t = threading.Thread(target=check_keyboard_interrupt)
t.start()

while True:
    print('Hello, World!')
    time.sleep(1)

Output

Hello, World!
Hello, World!
Hello, World!
Goodbye, World!

In this example, a while loop runs continuously and prints “Hello, World!” every second. However, when the user presses the Ctrl+C combination or the “break” key, the check_keyboard_interrupt() function is called, and the program exits gracefully by printing “Goodbye, World!”.

Conclusion

The KeyboardInterrupt error is a common issue in Python programming. However, with the methods discussed in this tutorial, you can easily handle the exception and exit your program gracefully. You can use a try-except block, the signal module, or the threading module to handle the KeyboardInterrupt exception in Python.

Leave a Reply

Your email address will not be published. Required fields are marked *