It seems to me that commonly you may want a Python program to print (usually to standard error) only the last line of the stack trace, e.g.:
IOError: Error reading file 'b'plunk'': b'failed to load external entity "plunk"'
I’ve got this solution:
def print_error(ex:Exception, file) -> None:
print('{0}: {1}'.format(ex.__class__.__name__, ex), file=file)
Example usage:
try:
crash in some manner
except Exception as ex:
print_error(ex, sys.stderr)
There is nothing particularly wrong with this, but this feature seems so basic that I can’t help but wonder if there isn’t a simpler way to do it. Am I missing something? Or is this a good solution?
I don’t know if there’s a better way of doing it, but considering that it’s all of 6 lines of code and I can’t imagine it takes long to carry out at all, I don’t think that you need a better one.