11

Is there anyway I can make my script execute one of my functions when Ctrl+c is hit when the script is running?

1

3 Answers 3

23

Take a look at signal handlers. CTRL-C corresponds to SIGINT (signal #2 on posix systems).

Example:

#!/usr/bin/env python
import signal
import sys
def signal_handler(signal, frame):
    print("You pressed Ctrl+C - or killed me with -2")
    sys.exit(0)
signal.signal(signal.SIGINT, signal_handler)
print("Press Ctrl+C")
signal.pause()
Sign up to request clarification or add additional context in comments.

3 Comments

note: this one should also hit the signal handler when you go kill -2 [pid] in the OS
@wim, good point, thanks, added a hint to my answer - is there actually a way to distinguish a kill by keyboard from a kill by kill?
I have seen the former will raise a KeyboardInterrupt exception in python, the latter won't. But I'm not sure on the implementation details of why this is so.
9

Sure.

try:
  # Your normal block of code
except KeyboardInterrupt:
  # Your code which is executed when CTRL+C is pressed.
finally:
  # Your code which is always executed.

Comments

3

Use the KeyboardInterrupt exception and call your function in the except block.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.