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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)) |
Leave a Reply