6

If I am running a python program on linux terminal and i abort it manually by pressing ctrl+c, how can i make my program do something when this event occurs.

something like:

if sys.exit():
    print "you chose to end the program"
Games Brainiac
  • 80,178
  • 33
  • 141
  • 199
Neha Verma
  • 63
  • 6
  • You have to use the `signal` module. http://stackoverflow.com/a/18115530/1688590 . Also note that checking `if sys.exit()` will immediatly shutdown your program. – xbello Jan 21 '14 at 08:11
  • 1
    @xbello since OP asks for exiting with `ctrl-C`, signal is not required. `KeyboardInterrupt` is sufficient. – Mp0int Jan 21 '14 at 08:15

3 Answers3

13

You can write a signal handling function

import signal,sys
def signal_handling(signum,frame):
    print "you chose to end the program"
    sys.exit()

signal.signal(signal.SIGINT,signal_handling)
while True:
    pass

pressing Ctrl+c sends a SIGINT interrupt which would output:

you chose to end the program

ravitejagv
  • 58
  • 4
Ashoka Lella
  • 6,631
  • 1
  • 30
  • 39
  • @TimPietzcker: Not, sure. This seems to be a valid answer though people are used to using `KeyBoardInterrupt` Exception. – Abhijit Jan 21 '14 at 08:32
  • 1
    @Abhijit: I would argue that a well-setup signal handler is nicer than having to wrap your entire program in a `try/except`. I guess it depends on what should happen if the user chooses *not* to abort the program. – Tim Pietzcker Jan 21 '14 at 08:34
  • @TimPietzcker: I have seen both styles but depends on your background. The Former is more Cish Style where SEH/C++ Exception handling was absent. The Later is more predominant in languages which supports exception handling. Only cases, which EH was not able to handle, single handlers were opted. So my take is its more to one's taste, style and preference. – Abhijit Jan 21 '14 at 08:41
8

Well, you can use KeyBoardInterrupt, using a try-except block:

try:
    # some code here
except KeyboardInterrupt:
    print "You exited

Try the following in your command line:

import time

try:
    while True:
        time.sleep(1)
        print "Hello"
except KeyboardInterrupt:
    print "No more Hellos"
Games Brainiac
  • 80,178
  • 33
  • 141
  • 199
1

Check the KeyboardInterrupt exception in Python.

You can put your code in a try block, catch the KeyboardInterrupt exception with except and let the user know that he has exited.

user2683246
  • 3,399
  • 29
  • 31
gravetii
  • 9,273
  • 9
  • 56
  • 75