Please can you review my standard exception handler for Python 3.x. It is located under the # +=+= line. The code above the line is to create an exception and so the code is code complete and runs standalone.
The code is just a standard exception formatter, so users are presented with easier to read messages rather than stack traces. This is a common idiom in many Python projects. But many / all don't format to the extent I have.
I have searched a lot, but I can't find anything better. I expected to find something on GitHub, but was unfruitful. If you find a way to improve this, please post it here so that I and others will know.
import inspect
import os
import sys
import traceback
if __name__ == '__main__':
try:
x = 42/0
# +=+=+=+=+=+=+=+=+=+=+=+=+=
except KeyboardInterrupt as e: # Ctrl-C
raise e
except SystemExit as e: # sys.exit()
raise e
except Exception as e :
exc_type, exc_obj, exc_tb = sys.exc_info()
scriptName = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
functionName = inspect.currentframe().f_code.co_name
print('=======================================================================================================')
print('Unhandled exception: ', exc_type, scriptName, 'at line', exc_tb.tb_lineno)
print(' in function', functionName)
print(' ', str(e))
traceback.print_exc()
sys.exit(1)