1

I would like the user to use control-c to close a script, but when control-c is pressed it shows the error and reason for close (which make sense). Is there a way to have my own custom output to the screen rather than what is shown? Not sure how to handle that specific error.

1

3 Answers 3

6

You could use try..except to catch KeyboardInterrupt:

import time

def main():
    time.sleep(10)

if __name__ == '__main__':
    try:
        main()
    except KeyboardInterrupt:
        print('bye')
Sign up to request clarification or add additional context in comments.

Comments

1

use the signal module to define a handler for the SIGINT signal:

import signal
import sys

def sigint_handler(signal_number, stack_frame):
    print('caught SIGINT, exiting')
    sys.exit(-1)

signal.signal(signal.SIGINT, sigint_handler)
raw_input('waiting...')

Comments

0

For general purpose code, handling the KeyboardInterrupt should suffice. For advanced code, such as threading, it is a whole different story. Here's a simple example.

http://docs.python.org/2/library/exceptions.html#exceptions.KeyboardInterrupt

try:
    while 1:
        x = raw_input("Type something or press CTRL+C to end: ")
        print repr(x)
except KeyboardInterrupt:
    print "\nWe're done here."

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.