KeyboardInterrrupt: Everything You Need to Know!

In this article, let us learn what KeyboardInterrupt is, and how to effectively handle it in our Python programs.

What is KeyboardInterrupt?

The KeyboardInterrupt is an exception in Python that is raised when the user presses a pre-defined key-combination while the program is executing. In most operating systems, ctrl + c is used as the combination.

This key combination is just a way to send a signal to the running program to ask it to stop the execution, do any clean-ups necessary, and end the program.

For example, run the following code in your system. During the execution, press ctrl+c when you wish to stop the execution.

import time

count = 0
while True:
    print(count)
    count += 1
    time.sleep(0.5) 

When you pressed ctrl+c, that sent a signal to the Python interpreter to end the program by raising a KeyboardInterrupt exception.

Now that we know how a KeyboardInterrupt gets raised, let us next learn how we should handle it.

How to handle KeyboardInterrupt?

Catching KeyboardInterrupts

Utilizing try-except blocks is the name of the game when it comes to dealing with exceptions. This is the same for handling the KeyboardInterrupt exception.

Enclose the main part of your program in the try block and keep the exception handling code to handle the interruption in the except block. In this way, the try block monitors the program for KeyboardInterrupt and the exception block handles the exit gracefully. 

Here’s what that will look like:

try:
    #your main code
except KeyboardInterrupt:
    #code that handles the interruption

So for instance, if the user presses ctrl+c when inputting something, the except block will take care of it:

try:
    name = input("What is your good name: ")
    print("Hello", name)
except KeyboardInterrupt:
    print("\nUh-oh program terminated! Pressing Ctrl+c leads to program termination!")

Here’s what would happen if the user enters their name:

What is your good name: Embedded Inventor
Hello Embedded Inventor

And here’s what would happen if the user presses ctrl+c:

What is your good name: ^C
Uh-oh program terminated! Pressing Ctrl+C leads to program termination!

As you can see, the user pressed Ctrl+C and the execution went to the except block, and the print statement in there got executed.

Now that we have learned how to catch KeyboardInterrupts, let us learn what kind of actions need to be done once the KeyboardInterrupt has been caught.

Performing necessary cleanup

The except block in your programs can be used to close any open files, devices, network connections, and other resources and we exit the program gracefully.

Let’s see an example:

try:
    f = open("myfile.txt", "r")
    content = f.read()
    print(content)
    f.close()

except KeyboardInterrupt:
    f.close()
    print("Terminating program...")
    raise sys.exit(1)

The above program is pretty simple,

  • we just open a file and try to read it.
  • During the process, if the user tries to exit the program, we catch the KeyboadInterrupt so it does not terminate the program while the file is still open.
  • Then we close the file in the except block to deallocate memory and
  • Once we have cleaned upa nd released all the resources we terminate the program by raising the sys.exit() method.

Exiting the program with the appropriate error code

When the program is closing down, it is best practice to exit the program with an error code that appropriately displays the exit status of the program.

So for example, if a program has no mistakes or problems in it, and the user wants to exit the program. We’ll use the sys.exit() method with error code 0 to indicate a successful program execution.

At the same time, unsuccessful program runs can be ended with the sys.exit() method again but by with a non-zero error-code.

We have written another article on this topic if you wish to learn how to exit programs like a professional.

How “NOT“ to handle KeyboardInterrupt

Just like there are some things to do when handling a KeyboardInterrupt, there are things which we must NOT do in the except block of KeyboardInterrupts.

Ignoring the user’s exit request

If the user requests to exit the program using ctrl+c, we must recognize it and close the program instead of just catching and ignoring it. 

try:
    #main program code 
except KeyboardInterrupt:
    #Ignoring the KeyboardInterrupt
    pass

Sure this might keep the program running but this disregards the user’s intentions as the user would have expected the program to be killed as soon as they press ctrl+c

Insufficient cleanup

Another mistake one might make is that they close the program as the user wants them to but they do not perform all the necessary cleanup activities beforehand.

This leads to open network connections, security risks, and unnecessary consumption of memory amongst many other side-effects.

Also it is worth noting that KeyboardInterrupt is not one of the most common exceptions you will run into in your daily life as a Python developer. Instead, you need to focus on 7 other errors mentioned in the article below if you wish to gain mastery in Python!

7 Most Common In-Built Exceptions in Python!

If you are a visual learner here is a YouTube video that we made on that same topic!

And with that, I will end this article.

Congratulations on making it to the end of the article, not many have the perseverance to do so!

I hope you enjoyed reading this article and found it useful!

Feel free to share it with your friends and colleagues!

If your thirst for knowledge has not been quenched yet, here are some related articles that might spark your interest!

Related Articles

SyntaxError: A Step By Step Troubleshooting Guide!

NameError: A Step By Step Troubleshooting Guide!

SyntaxError: A Step By Step Troubleshooting Guide!

AttributeError: A Step By Step Troubleshooting Guide!

FileNotFoundError: A Step By Step Troubleshooting Guide!

ModuleNotFoundError: A Step By Step Troubleshooting Guide!

Thanks to Namazi Jamal for his contributions in writing this article!

Photo of author
Editor
Balaji Gunasekaran
Balaji Gunasekaran is a Senior Software Engineer with a Master of Science degree in Mechatronics and a bachelor’s degree in Electrical and Electronics Engineering. He loves to write about tech and has written more than 300 articles. He has also published the book “Cracking the Embedded Software Engineering Interview”. You can follow him on LinkedIn