From: Oleg Broytman Date: Tue, 19 Apr 2016 10:51:31 +0000 (+0300) Subject: init.py: colorize traceback in pager X-Git-Url: https://git.phdru.name/?a=commitdiff_plain;h=058002bd47ad258567d8027e645ac60d59b2bda8;p=dotfiles.git init.py: colorize traceback in pager --- diff --git a/lib/python/init.py b/lib/python/init.py index 69b9ac1..a5e6323 100644 --- a/lib/python/init.py +++ b/lib/python/init.py @@ -114,16 +114,19 @@ def init(): else: try: locale.setlocale(locale.LC_ALL, '') - except (ImportError, locale.Error): pass # no locale support or unsupported locale # set displayhook from pprint import pprint + pager = os.environ.get("PAGER") or 'more' - class BasePPrintPager: - def pipe(self, value): + class BasePager: + def write(self, value): + self.stdin.write(value) + + def pprint(self, value): pprint(value, stream=self.stdin) def close(self): @@ -132,35 +135,37 @@ def init(): try: from subprocess import Popen, PIPE except ImportError: - class PPrintPager(BasePPrintPager): + class Pager(BasePager): def __init__(self): self.pipe = Popen(pager, shell=True, stdin=PIPE) self.stdin = self.pipe.stdin def close(self): - BasePPrintPager.close(self) + BasePager.close(self) self.pipe.wait() else: - class PPrintPager(BasePPrintPager): + class Pager(BasePager): def __init__(self): self.stdin = os.popen(pager, 'w') - pager = os.environ.get("PAGER") or 'more' def displayhook(value): if value is not None: __builtin__._ = value - pprint_pager = PPrintPager() - pprint_pager.pipe(value) - pprint_pager.close() + pager = Pager() + pager.pprint(value) + pager.close() sys.displayhook = displayhook - from traceback import print_exception + from traceback import format_exception def excepthook(etype, evalue, etraceback): - pprint_pager = PPrintPager() - print_exception(etype, evalue, etraceback, file=pprint_pager.stdin) - pprint_pager.close() + lines = format_exception(etype, evalue, etraceback) + pager = Pager() + for line in lines: + pager.write( + '\033[31m' + line.rstrip('\n') + '\033[0m\n') # red, reset + pager.close() sys.excepthook = excepthook