display.py 699 B

123456789101112131415161718192021222324
  1. """
  2. pprint and pformat wrappers with colorization support
  3. """
  4. from __future__ import print_function
  5. import sys
  6. from pprint import pformat as pformat_
  7. def _colorize(text, colorize=True):
  8. if not colorize or not sys.stdout.isatty():
  9. return text
  10. try:
  11. from pygments import highlight
  12. from pygments.formatters import TerminalFormatter
  13. from pygments.lexers import PythonLexer
  14. return highlight(text, PythonLexer(), TerminalFormatter())
  15. except ImportError:
  16. return text
  17. def pformat(obj, *args, **kwargs):
  18. return _colorize(pformat_(obj), kwargs.pop('colorize', True))
  19. def pprint(obj, *args, **kwargs):
  20. print(pformat(obj, *args, **kwargs))