noobyy
noobyy

Reputation: 143

Python cancel process using ctrl + c without quitting program?

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

Answers (2)

tdelaney
tdelaney

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

Thymen
Thymen

Reputation: 2159

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!")

Upvotes: 1

Related Questions