Python snippet: nicer Python tracebacks
Python exceptions are really helpful but they're also rather ugly. Here's a mean one I encountered today. Don't try to interpret it -- it's only here to show off its ugliness:
I wanted it to look more like this:
So I wrote some code to do that. Specifically, the exception formatter I wrote does the following:
- Prints only the 5 deepest stack frames (older frames are usually noise)
- Prints code from only the 3 deepest stack frames (same reasoning)
- Prints as little of the file name as possible -- the .py suffix is removed, as is any directory information above the current working directory
- Prints file names and method names lined up, one after the other. Note that the messy traceback above almost does this already, but that's just luck.
- If Pygments is installed, syntax-highlights the code.
All of the above is, of course, configurable.
Here's the code:
import bettertb bettertb.run(your_main_function, arg1, arg2, ...)
This is a pretty quick and dirty work in progress, so email me (nicholas at lardcave) if you have suggestions, fixes, etc. The first major problem is that getting tracebacks is now more rewarding than having the code finish successfully.