]> git.phdru.name Git - dotfiles.git/commitdiff
init.py: refactor paging
authorOleg Broytman <phd@phdru.name>
Tue, 19 Apr 2016 10:27:21 +0000 (13:27 +0300)
committerOleg Broytman <phd@phdru.name>
Tue, 19 Apr 2016 10:27:21 +0000 (13:27 +0300)
lib/python/init.py

index c0afb68ad39e4cc15ec15b7dde07e9d1d7d136ef..15bcb32596c22a22b8768f215dc208a7117db1bd 100644 (file)
@@ -121,29 +121,56 @@ def init():
     # set displayhook
 
     from pprint import pprint
+
+    class BasePPrintPager:
+        def pipe(self, value):
+            pprint(value, stream=self.stdin)
+
+        def close(self):
+            self.stdin.close()
+
     try:
         from subprocess import Popen, PIPE
     except ImportError:
-        use_subprocess = False
+        class PPrintPager(BasePPrintPager):
+            def __init__(self):
+                self.pipe = Popen(pager, shell=True, stdin=PIPE)
+                self.stdin = self.pipe.stdin
+
+            def close(self):
+                BasePPrintPager.close(self)
+                self.pipe.wait()
     else:
-        use_subprocess = True
+        class PPrintPager(BasePPrintPager):
+            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
-            if use_subprocess:
-                _pipe = Popen(pager, shell=True, stdin=PIPE)
-                pipe = _pipe.stdin
-            else:
-                pipe = os.popen(pager, 'w')
-            pprint(value, stream=pipe)
-            pipe.close()
-            if use_subprocess:
-                _pipe.wait()
+        pprint_pager = PPrintPager()
+        pprint_pager.pipe(value)
+        pprint_pager.close()
 
     sys.displayhook = displayhook
 
+    from traceback import print_exception
+
+    def excepthook(etype, evalue, etraceback):
+        print_exception(etype, evalue, etraceback)
+
+    sys.excepthook = excepthook
+
+    # From Thomas Heller:
+    # https://mail.python.org/pipermail/python-list/2001-April/099020.html
+
+    # import pdb
+    #
+    # def info(*args):
+    #    pdb.pm()
+    # sys.excepthook = info
+
     # utilities
 
     # From: Paul Magwene:
@@ -181,15 +208,6 @@ def init():
     __builtin__.ls = DirLister()
     __builtin__.cd = DirChanger()
 
-    # From Thomas Heller:
-    # https://mail.python.org/pipermail/python-list/2001-April/099020.html
-
-    # import pdb
-    #
-    # def info(*args):
-    #    pdb.pm()
-    # sys.excepthook = info
-
     # print working directory
 
     class Pwd: