#100daysofcode :: Python 3.0 , interrupting an endless loop from the keyboard,gracefully

Recently I started out on a mission to further hone my programming skills. Out of the courses that I explored online, the #100daysofcode course from the TalkPython folks appealed to me the most. It is challenging,structured and the instructors are great.

I will be blogging my micro-learnings onthis journey. This is the first one from Day #3

I was in a situation where I had to execute a piece of code and output it’s  result on the console until the flow is interrupted by the user (through the console)

Ctrl+C can achieve it .However the interruption was not graceful, it resulted in my Python program “crashing”. So, I had handle this through exception handling.

Here the code that I wrote to handle the keyboard interrupt gracefully


try:
start_time = datetime.now()
#do something endlessly
while True:
print(datetime.now())
time.sleep(1)
# until interrupted by the keyboard
except KeyboardInterrupt:
#behave gracefully in case of interruption
time_lapsed = (datetime.now() start_time)
print('Time elapsed (hh:mm:ss.ms) {}'.format(time_lapsed))

view raw

interrupt.py

hosted with ❤ by GitHub


 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s