0

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!'
noobyy
  • 123
  • 9
  • You can wrap your function in a `try` `except` block and listen for the `KeyboardInterrupt`, similar to [this](https://stackoverflow.com/questions/21120947/catching-keyboardinterrupt-in-python-during-program-shutdown) post. – Thymen Nov 29 '20 at 19:01
  • thanks, it worked, post as answer and I'll accept it – noobyy Nov 29 '20 at 19:04

2 Answers2

1

You can wrap your function in a try except block and listen for the KeyboardInterrupt, similar to this post.

Full code:

def sleep():
    try:
        time.sleep(3600)
    except KeyboardInterrupt:
        pass

print("Hello!")
Thymen
  • 2,089
  • 1
  • 9
  • 13
1

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)
tdelaney
  • 73,364
  • 6
  • 83
  • 116