Today seems to be a fine day to learn about KeyboardInterrupt. If you read this articleI 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 exceptionsfor 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). Finallyblock always gets executedgenerally used for handling external resources. For instancedatabase connectivityclosing a fileetc. If there isn’t any exceptioncode in the else block will also run.

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 keyboardswhen 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 beginsprinting and incrementing the value of count. Ctrl + c keyboard shortcut; will interrupt the program. For this reasonprogram execution comes to a halt. A KeyboardInterrupt message is shown on the screen.

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 coderan 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 + cpython interpretor detects an keyboard interrupt and halts the program mid execution.
- After thatfinally block finishes its execution.

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(signalframe):
print('\nYou pressed Ctrl+CkeyboardInterrupt detected!')
sys.exit(0)
signal.signal(signal.SIGINTsignal_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.

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 filesnamelyprocess.py and test.py. In the process.py filethere 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 + cpython interpretor detects an keyboard interrupt and halts the program mid execution. Later handled by the except block.

FAQs on KeyboardInterrupt
To prevent traceback from popping upyou need to handle the KeyboardInterrupt exception in the except block.try:
while True:
print("Running program…")
except KeyboardInterrupt:
print("caught keyboard interrupt")
If a cell block takes too much time to executeclick on the kernel optionthen restart the kernel 0,0 option.
When using the flask framework use these functions.
Windows : netstat -ano | findstr
Linux: netstat -nlp | grep
macOS: lsof -P -i :
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 exceptionstry-catch blocksusage of finallyand 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.
![[Fixed] nameerror: name Unicode is not defined](https://www.pythonpool.com/wp-content/uploads/2024/01/Fixed-nameerror-name-Unicode-is-not-defined-300x157.webp)
![[Solved] runtimeerror: cuda error: invalid device ordinal](https://www.pythonpool.com/wp-content/uploads/2024/01/Solved-runtimeerror-cuda-error-invalid-device-ordinal-300x157.webp)
![[Fixed] typeerror can’t compare datetime.datetime to datetime.date](https://www.pythonpool.com/wp-content/uploads/2024/01/typeerror-cant-compare-datetime.datetime-to-datetime.date_-300x157.webp)
![[Fixed] typeerror: type numpy.ndarray doesn’t define __round__ method](https://www.pythonpool.com/wp-content/uploads/2024/01/Fixed-typeerror-type-numpy.ndarray-doesnt-define-__round__-method-300x157.webp)