KeyboardInterrupt exeption handling with time.sleep

Viewed 223
  • I am going to display current time every 2 seconds and exception handling.
  • If there is KeyboardInterrupt, message should display like print('Program is stopped'). But in my code, try/except isn`t working.So how can I print message like 'Stopped'?
from datetime import datetime
import time

def display_time():
    time.sleep(2)
    current_time = datetime.now()
    print('Time: ', current_time.strftime("%X"))

try:
    while True:
        display_time()
except KeyboardInterrupt:
    print('Stopped')
print('Program ends')
1 Answers

You should check if Ctrl-C is pressed inside the while loop and, if so break outside the loop:

while True:
    try:
        display_time()
    except KeyboardInterrupt:
        print("Stopped")
        break

print('Program ends')

Related