How To Keyboard Interrupt Python

When working with Python, you may encounter situations where you need to stop a running script or program immediately. This could be due to an infinite loop, a bug causing the script to hang, or any other reason. In such cases, knowing how to interrupt the execution of a Python script is essential. This blog post will cover different ways to perform a keyboard interrupt in Python, which can help you save time and prevent unwanted resource consumption.

Method 1: Using Ctrl+C

For most platforms and terminals, the most straightforward way to interrupt the execution of a Python script is by pressing the Ctrl and C keys simultaneously. This combination sends a SIGINT (Signal Interrupt) signal to the Python process, causing it to stop.

For example, let’s consider a simple Python script that enters an infinite loop:

while True:
    print("Hello, World!")

While running this script, pressing Ctrl+C in the terminal or command prompt will immediately stop the script and display a KeyboardInterrupt message.

Method 2: Handling KeyboardInterrupt Exception

Sometimes, you may want to gracefully handle the keyboard interrupt and perform certain actions before the script stops. In such cases, you can use a try and except block to catch the KeyboardInterrupt exception.

Here’s an example of how to handle a keyboard interrupt in a Python script:

try:
    while True:
        print("Hello, World!")
except KeyboardInterrupt:
    print("nUser interrupted the script. Exiting...")

In this example, pressing Ctrl+C will trigger the except block, allowing you to perform any necessary clean-up before the script exits.

Method 3: Using time.sleep()

In some cases, you may want to give your Python script a break or pause between iterations. This can be achieved using the time.sleep() function, which can also make it easier for the script to respond to a keyboard interrupt.

Here’s an example of how to use time.sleep() in your script:

import time

try:
    while True:
        print("Hello, World!")
        time.sleep(1)
except KeyboardInterrupt:
    print("nUser interrupted the script. Exiting...")

In this example, the script will pause for 1 second after printing “Hello, World!” each time. This makes it more responsive to keyboard interrupts, allowing the script to exit more quickly when Ctrl+C is pressed.

Conclusion

There are several ways to interrupt the execution of a Python script, with the most common method being the keyboard combination of Ctrl+C. Additionally, you can handle keyboard interrupts using try and except blocks, or make your script more responsive to interrupts by introducing pauses using the time.sleep() function. These methods can help you manage your Python scripts more effectively and avoid potential issues caused by unresponsive or hanging processes.