Understand KeyboardInterrupt in Python Before You Regret

Today seems to be a fine day to learn about KeyboardInterrupt. If you read this article, I can deduce that you have some proficiency with exceptions and exception handling. Don’t sweat it even if you have no knowledge about them; we will give you a brief refresher.

Exceptions are errors that may interrupt the flow of your code and end it prematurely; before even completing its execution. Python has numerous built-in exceptions which inherit from the BaseException class. Check all built-in exceptions from here.

Try-catch blocks handle exceptions, for instance:

try:
	div_by_zero = 10/0
except Exception as e:
	print(f"Exception name:{e}")
else:
     print("I would have run if there wasn't any exception")
finally:
	print("I will always run!")

The big idea is to keep that code into a try block which may throw an exception. Except block will catch that exception and do something(statements defined by the user). Finally, block always gets executed, generally used for handling external resources. For instance, database connectivity, closing a file, etc. If there isn’t any exception, code in the else block will also run.

try-catch-finally example
Catching exception

What is Keyboard Interrupt Exception?

KeyboardInterrupt exception is a part of Python’s built-in exceptions. When the programmer presses the ctrl + c or ctrl + z command on their keyboards, when present in a command line(in windows) or in a terminal(in mac os/Linux), this abruptly ends the program amidst execution.

Looping until Keyboard Interrupt

count = 0
whilte True:
    print(count)
    count += 1

Try running this code on your machine.

An infinite loop begins, printing and incrementing the value of count. Ctrl + c keyboard shortcut; will interrupt the program. For this reason, program execution comes to a halt. A KeyboardInterrupt message is shown on the screen.

KeyboardInterrupt exception thrown
KeyboardInterrupt exception thrown

Python interpreter keeps a watch for any interrupts while executing the program. It throws a KeyboardInterrupt exception whenever it detects the keyboard shortcut Ctrl + c. The programmer might have done this intentionally or unknowingly.

Catching/Handling KeyboardInterrupt

try:
	while True:
		print("Program is running")
except KeyboardInterrupt:
	print("Oh! you pressed CTRL + C.")
	print("Program interrupted.")
finally:
    print("This was an important code, ran at the end.")

Try-except block handles keyboard interrupt exception easily.

  • In the try block a infinite while loop prints following line- “Program is running”.
  • On pressing ctrl + c, python interpretor detects an keyboard interrupt and halts the program mid execution.
  • After that, finally block finishes its execution.
Handling keyboard interrupt using try-except-finally
Handling keyboard interrupt using try-except-finally

Catching KeyboardInterrupt using Signal module

Signal handlers of the signal library help perform specific tasks whenever a signal is detected.

import signal
import sys
import threading

def signal_handler(signal, frame):
    print('\nYou pressed Ctrl+C, keyboardInterrupt detected!')
    sys.exit(0)

signal.signal(signal.SIGINT, signal_handler)
print('Enter Ctrl+C to initiate keyboard iterrupt:')
forever_wait = threading.Event()
forever_wait.wait()

Let’s breakdown the code given above:

  • SIGINT reperesents signal interrupt. The terminal sends to the process whenever programmer wants to interrupt it.
  • forever_wait event waits forever for a ctrl + c signal from keyboard.
  • signal_handler function on intercepting keyboard interrupt signal will exit the process using sys.exit.
Catching keyboard interrupt using Signal module
Catching keyboard interrupt using Signal module

Subprocess KeyboardInterrupt

A subprocess in Python is a task that a python script assigns to the Operative system (OS).

process.py

while True:
	print(f"Program {__file__} running..")

test.py

import sys
from subprocess import call

try:
    call([sys.executable, 'process.py'], start_new_session=True)
except KeyboardInterrupt:
    print('[Ctrl C],KeyboardInterrupt exception occured.')
else:
    print('No exception')

Let’s understand the working of the above codes:

  • We have two files, namely, process.py and test.py. In the process.py file, there is an infinite while loop which prints “Program sub_process.py running”.
  • In the try block sys.executeble gives the path to python interpretor to run our subprocess which is process.py.
  • On pressing ctrl + c, python interpretor detects an keyboard interrupt and halts the program mid execution. Later handled by the except block.
Python Subprocess KeyboardInterrupt
Python subprocess KeyboardInterrupt

FAQs on KeyboardInterrupt 

How to prevent traceback on keyboard interrupt?

To prevent traceback from popping up, you need to handle the KeyboardInterrupt exception in the except block.
try:
while True:
print("Running program…")
except KeyboardInterrupt:
print("caught keyboard interrupt")

KeyboardInterrupt in jupyter notebook

If a cell block takes too much time to execute, click on the kernel option, then restart the kernel 0,0 option.

Flask keyboard interrupt, closing flask application?

When using the flask framework use these functions.
Windows : netstat -ano | findstr
Linux: netstat -nlp | grep
macOS: lsof -P -i :

Interrupt in multiprocessing pool?

This is a Python bug. When waiting for a condition in threading.Condition.wait(), KeyboardInterrupt is never sent.
import threading
cond = threading.Condition(threading.Lock()) cond.acquire()
cond.wait(None) print "done"

Conclusion

This article briefly covered topics like exceptions, try-catch blocks, usage of finally, and else. We also learned how keyboard interrupt could abruptly halt the flow of the program. Programmers can use it to exit a never-ending loop or meet a specific condition. We also covered how to handle keyboard interrupt using try-except block in Python. Learned about another way to catch keyboard interrupt exception and interrupted a subprocess.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments