Reputation: 143
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
def sleep():
time.sleep(3600)
print("Hello!")
.
>Start program
>Hit ctrl + c 10 seconds later,
>Program prints 'Hello!'
Upvotes: 0
Views: 557
Reputation: 77337
As mentioned, you can catch the keyboard interrupt. As an additional wrinkle, its common to let 2 ctrl-c presses terminate the program. In this example, if user hits the eject button twice in 2 seconds, we really do exit.
import time
kb_interrupt_time = 0.0
for i in range(100):
try:
time.sleep(1)
except KeyboardInterrupt:
now = time.time()
if now - kb_interrupt_time < 2:
print("done")
raise
print("interrupted")
kb_interrupt_time = now
print("beep", i)
Upvotes: 1