Rather than using
as ethenraise eyou can just omite.except KeyboardInterrupt as e: raise eexcept KeyboardInterrupt: raiseRather than specifying an except block for
KeyboardInterruptandSystemExityou can just specify them in the sameexceptby passing a tuple.except KeyboardInterrupt: raise except SystemExit: raiseexcept (KeyboardInterrupt, SystemExit): raiseBoth
KeyboardInterruptandSystemExitare not subclasses ofExceptionso you do not need to handle them. The exceptions will propagate like normal.You may want to familiarize yourself with the exception hirarchyhierarchy.
You can get all the information that
sys.exc_info()gives frome.exc_type, exc_obj, exc_tb = sys.exc_info()exc_type, exc_obj, exc_tb = type(e), e, e.__traceback__You can get the current frame from
exc_tbrather thaninspect.currentframe(). This makes the code more portable if you ever decide to move the code into a function to format tracebacks.frame = inspect.currentframe()frame = exc_tb.tb_framePlease follow PEP 8 and name variables with
snake_case. It is very easy to see the code you've taken from the Python docs and the code you've written yourself / taken from somewhere else.If you're going to hard code the
==at least use*to build it the size you want.print('=======================================================================================================')print('=' * 103)Better yet just print to the size of the terminal.
print('=' * os.get_terminal_size().columns)I would prefer to use f-strings if available.
print('Unhandled exception: ', exc_type, script_name, 'at line', exc_tb.tb_lineno)print(f'Unhandled exception: {exc_type} {script_name} at line {exc_tb.tb_lineno}')