Python global exception handling
If this is a script for execution on the command line, you can encapsulate your run-time logic in main()
, call it in an if __name__ == '__main__'
and wrap that.
if __name__ == '__main__':
try:
main()
except KeyboardInterrupt:
print 'Killed by user'
sys.exit(0)
You could change sys.excepthook
if you really don't want to use a try/except
.
import sys
def my_except_hook(exctype, value, traceback):
if exctype == KeyboardInterrupt:
print "Handler code goes here"
else:
sys.__excepthook__(exctype, value, traceback)
sys.excepthook = my_except_hook