SIGINT and exception handling in Python

import signal
import sys
import time

def sigint_handler(signal, frame):
    print "signal"
    sys.exit(0)

signal.signal(signal.SIGINT, sigint_handler)

while 1:
    try:
        print "text"
        time.sleep(2)
    except KeyboardInterrupt:
        print "keybi"
        exit(0)
    except:
        print "except"
        continue

When I click Ctrl-C, I see “signal” and “exception”, and the program does not exit.

  • Why doesn't the program exit the program until it apparently reaches sys.exit(0)?

  • Why does the program stream not reach the partition KeyboardInterrupt?

  • What is the short way to make it Ctrl-Cwork and handle each case except:separately in different places without a way out?

+4
source share
2 answers

The program does not exit because it sys.exitworks by throwing an exception SystemExit, and your blanket exceptcaught it.

except KeyboardInterrupt , SIGINT, , SIGINT, SIGINT KeyboardInterrupt Ctrl-C.

, , .

+6

@user2357112 , . MyError SIGINT.

import signal
import time

class MyError(Exception): 
    pass

def handler(sig, frame):
    raise MyError('Received signal ' + str(sig) +
                  ' on line ' + str(frame.f_lineno) +
                  ' in ' + frame.f_code.co_filename)    

signal.signal(signal.SIGINT, handler)

try:
    while 1:
        time.sleep(1)        # Hit <CTRL>+C here
except KeyboardInterrupt:
    print('Keyboard interrupt caught')
except MyError as err:
    print("Hiccup:",err)
    # do stuff

print('Clean exit')

signal.signal(), KeyboardInterrupt, .

+1

All Articles