Skip to content

Instantly share code, notes, and snippets.

@akatrevorjay
Last active October 12, 2017 15:56
Show Gist options
  • Save akatrevorjay/c511f23a8afdb176811a3cb1b5ecf38f to your computer and use it in GitHub Desktop.
Save akatrevorjay/c511f23a8afdb176811a3cb1b5ecf38f to your computer and use it in GitHub Desktop.
A pprint that doesn't suck
import six
import sys
import pygments
from pprint import pformat
STYLE = pygments.styles.get_style_by_name('monokai')
FORMATTER = pygments.formatters.get_formatter_by_name('console16m', style=STYLE)
LEXER_PYTHON = pygments.lexers.get_lexer_by_name('python{}'.format(six.PY3 and '3' or ''))
def pf(arg, lexer=LEXER_PYTHON, formatter=FORMATTER):
"""Pretty formats with coloring.
Works in iPython, but not bpython as it does not write directly to term
and decodes it instead."""
arg = pformat(arg)
return pygments.highlight(arg, lexer, formatter)
def pp(arg, lexer=LEXER_PYTHON, formatter=FORMATTER, outfile=sys.stdout):
"""Pretty prints with coloring.
Works in iPython, but not bpython as it does not write directly to term
and decodes it instead."""
arg = pformat(arg)
close = False
try:
if isinstance(outfile, six.string_types):
close = True
outfile = open(outfile, 'w')
pygments.highlight(arg, lexer, formatter, outfile)
finally:
if close:
outfile.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment