Skip to content
Advertisement

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!'

Advertisement

Answer

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!")
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement