I want to be able to quit a action my program is preforming by hitting ctrl + c, but without quitting the program entirely. I’m sure there is a thread about this somewhere, but I couldn’t find anything related to what I want. Here is what I want
JavaScript
x
5
1
def sleep():
2
time.sleep(3600)
3
4
print("Hello!")
5
.
JavaScript
1
4
1
>Start program
2
>Hit ctrl + c 10 seconds later,
3
>Program prints 'Hello!'
4
Advertisement
Answer
You can wrap your function in a try except block and listen for the KeyboardInterrupt, similar to this post.
Full code:
JavaScript
1
8
1
def sleep():
2
try:
3
time.sleep(3600)
4
except KeyboardInterrupt:
5
pass
6
7
print("Hello!")
8