Python Exceptions – Exit running code with a key stroke

In this post we will be creating a Python script that will stop running at the press of a key stroke. For this example we will be using the Python’s built in exceptions to stop our code.

See below where we have a for loop that will continuously increment and print a number.

import time

Count=0

while True:
    Count+=1
    print(Count)
    time.sleep(1)

With the snippet of code below, pressing ‘CTRL’ + ‘C’ will cause Python to raise a keyboard interrupt and stop the running of the code.

import time

Count=0
try:
    while True:
        Count+=1
        print(Count)
        time.sleep(1)
except KeyboardInterrupt:
    pass

Using Pythons built-in exceptions the ‘CONTROL’ + ‘C’ key combination will force the above to stop running.

Leave a Reply