Highlighting python stack traces

Take a look at Supercat (spc). It does both ANSI and HTML highlighting and can be configured for your particular output. It comes with some configuration files for source code files in C and Python, for example and log files, Changelogs, diffs and others.

Based on Dave Kirby's suggestion for vim, this does something similar:

less -p regex file_name

Or

some_command | less -p regex

There is a nice module just for that purpose:

  • colored-traceback @ github
  • colored-traceback @ pypi

You just have to download and install it via pip:

pip install colored-traceback

Import it into a top-level file of your project, for exmaple like this:

if DEBUG:
    import colored_traceback
    colored_traceback.add_hook()

And you get a traceback like that for every underling file (colors vary):

Traceback (most recent call last):
  File "./workflowy.py", line 525, in <module>
    main()
  File "./workflowy.py", line 37, in main
    projects = cli.load_json(args, input_is_pipe)
  File "./workflowy.py", line 153, in load_json
    return json.load(sys.stdin)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py", line 290, in load
    **kw)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py", line 338, in loads
    return _default_decoder.decode(s)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 365, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 383, in raw_decode
    raise ValueError("No JSON object could be decoded")
ValueError: No JSON object could be decoded

Actually, there is a great Python syntax highlighting library called Pygments, which is also able to highlight tracebacks.

So, all you have to do is:

$ easy_install pygments # downloads and installs pygments
$ cat traceback.txt | pygmentize -l pytb

"pytb" is the shortcut for the PythonTracebackLexer. There is also a special lexer for Python 3 Tracebacks included, which is called "py3tb".

You can format the output in various formats (including html, latex, svg, several image formats and so on). But there is also a terminal formatter available (and if you are wondering... of course there are different color themes available!).

You can use -f html to select another formatter (in that case, the HTML formatter).