Kye Kye - 17 days ago 8
Python Question

Python Global Exception Handling

So I want to catch

KeyboardInterrupt
globally, and deal with it nicely. I don't want to encase my entire script in a huge try/except statement, because that just sounds gross. Is there any way to do this?

Answer

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)