]> git.phdru.name Git - dotfiles.git/blobdiff - lib/python/init.py
init.py: Hide errors during `.write_history_file()`
[dotfiles.git] / lib / python / init.py
index 44aebe49725066875ba2aa146f619a3e973f7c02..8720caa9bf1120075310a8a54296704b47e7332b 100644 (file)
@@ -4,15 +4,23 @@
 # into your .profile (use whatever syntax and initialization file
 # is appropriate for your shell):
 #
-# PYTHONSTARTUP=$HOME/init.py # or where you really put it
+# PYTHONSTARTUP=$HOME/init.py  # or where you really put it
 # export PYTHONSTARTUP
 
+
 def init():
-    import sys, os
-    import __builtin__
+    try:
+        import __builtin__ as builtins
+    except ImportError:
+        import builtins
+    import os
+    import sys
+
+    # readline/pyreadline
 
-    pyreadlinew32_startup = os.path.join(sys.prefix,
-        'lib', 'site-packages', 'pyreadline', 'configuration', 'startup.py')
+    pyreadlinew32_startup = os.path.join(
+        sys.prefix, 'lib', 'site-packages',
+        'pyreadline', 'configuration', 'startup.py')
 
     if os.path.exists(pyreadlinew32_startup):
         execfile(pyreadlinew32_startup)
@@ -22,35 +30,54 @@ def init():
         # https://mail.python.org/pipermail/python-list/2001-March/062888.html
 
         try:
-            import rlcompleter, readline
-            initfile = os.environ.get('INPUTRC') or os.path.expanduser('~/.inputrc')
+            import rlcompleter  # noqa: need for completion
+            import readline
+            initfile = os.environ.get('INPUTRC') \
+                or os.path.expanduser('~/.inputrc')
             readline.read_init_file(initfile)
 
-            histfile = os.path.expanduser('~/.python-history')
-            try:
-                readline.read_history_file(histfile)
-            except IOError:
-                pass # No such file
+            # if 'libedit' in readline.__doc__:
+            #     readline.parse_and_bind("bind ^I rl_complete")
+            # else:
+            #     readline.parse_and_bind("tab: complete")
+
+            histfiles = ['~/.python_history']
+            # if 'VIRTUAL_ENV' in os.environ:
+            #     histfiles.append('$VIRTUAL_ENV/.python_history')
+            for histfile in histfiles:
+                try:
+                    histfile = os.path.expandvars(histfile)
+                    histfile = os.path.expanduser(histfile)
+                    readline.read_history_file(histfile)
+                except IOError:
+                    pass  # No such file
 
             def savehist():
-                histfilesize = os.environ.get('HISTFILESIZE') or \
-                               os.environ.get('HISTSIZE')
-                if histfilesize:
+                histsize = os.environ.get('HISTSIZE')
+                if histsize:
                     try:
-                        histfilesize = int(histfilesize)
+                        histsize = int(histsize)
                     except ValueError:
                         pass
                     else:
-                        readline.set_history_length(histfilesize)
-                readline.write_history_file(histfile)
+                        readline.set_history_length(histsize)
+                histfile = histfiles[-1]
+                histfile = os.path.expandvars(histfile)
+                histfile = os.path.expanduser(histfile)
+                try:
+                    readline.write_history_file(histfile)
+                except IOError:
+                    pass
 
             import atexit
             atexit.register(savehist)
 
         except (ImportError, AttributeError):
-            pass # no readline or atexit, or readline doesn't have
-                 # {read,write}_history_file - ignore the error
+            # no readline or atexit, or readline doesn't have
+            # {read,write}_history_file - ignore the error
+            pass
 
+    # terminal
 
     term = os.environ.get('TERM', '')
     if 'linux' in term:
@@ -61,25 +88,28 @@ def init():
     # From Randall Hopper:
     # https://mail.python.org/pipermail/python-list/2001-March/112696.html
 
+    _term_found = False
     for _term in ['linux', 'rxvt', 'screen', 'term', 'vt100']:
-        if _term not in term:
-            continue
+        if _term in term:
+            _term_found = True
+            break
 
+    if _term_found:
         if background == 'dark':
-            ps1_color = '3' # yellow
-            stdout_color = '7' # bold white
+            ps1_color = '3'  # yellow
+            stdout_color = '7'  # bold white
         else:
-            ps1_color = '4' # blue
-            stdout_color = '0' # bold black
+            ps1_color = '4'  # blue
+            stdout_color = '0'  # bold black
 
         sys.ps1 = '\001\033[3%sm\002>>>\001\033[0m\002 ' % ps1_color
-        sys.ps2 = '\001\033[1;32m\002...\001\033[0m\002 ' # bold green
-
+        sys.ps2 = '\001\033[1;32m\002...\001\033[0m\002 '  # bold green
 
         # From Denis Otkidach
 
         class ColoredFile:
-            def __init__(self, fp, begin, end='\033[0m'): # reset all attributes
+            def __init__(self, fp, begin,
+                         end='\033[0m'):  # reset all attributes
                 self.__fp = fp
                 self.__begin = begin
                 self.__end = end
@@ -94,30 +124,123 @@ def init():
                 return getattr(self.__fp, attr)
 
         sys.stdout = ColoredFile(sys.stdout, '\033[1;3%sm' % stdout_color)
-        sys.stderr = ColoredFile(sys.stderr, '\033[31m') # red
+        sys.stderr = ColoredFile(sys.stderr, '\033[31m')  # red
+
+        def myinput(prompt=None):
+            save_stdout = sys.stdout
+            sys.stdout = sys.__stdout__
+            try:
+                result = builtin_input(prompt)
+            except EOFError:
+                result = None
+            sys.stdout = save_stdout
+            return result
 
-        break
+        try:
+            builtins.raw_input
+        except AttributeError:  # PY3
+            builtin_input = builtins.input
+            builtins.input = myinput
+        else:
+            builtin_input = builtins.raw_input
+            builtins.raw_input = myinput
 
     try:
         import locale
     except ImportError:
-        pass # locale was not compiled
+        pass  # locale was not compiled
     else:
         try:
             locale.setlocale(locale.LC_ALL, '')
+        except (ImportError, locale.Error):
+            pass  # no locale support or unsupported locale
 
-            from pprint import pprint
+    # set displayhook and excepthook
 
-            def displayhook(value):
-                if value is not None:
-                    __builtin__._ = value
-                    pprint(value)
+    from pprint import pprint
+    from traceback import format_exception, print_exc
 
-            sys.displayhook = displayhook
+    pager = os.environ.get("PAGER") or 'more'
 
-        except (ImportError, locale.Error):
-            pass # no locale support or unsupported locale
+    # if your pager is 'less', options '-F' and '-R' must be passed to it,
+    # and option '-X' is very much recommended
+    if pager == 'less':
+        less = os.environ.get("LESS") or ''
+        for opt in 'X', 'R', 'F':
+            if opt not in less:
+                less = opt + less
+        os.environ["LESS"] = less
+
+    class BasePager:
+        def write(self, value):
+            self.stdout.write(value)
+
+        def pprint(self, value):
+            pprint(value,
+                   stream=ColoredFile(self.stdout,
+                                      '\033[1;3%sm' % stdout_color))
+
+        def close(self):
+            self.stdout.close()
+
+    try:
+        from subprocess import Popen, PIPE
+    except ImportError:
+        class Pager(BasePager):
+            def __init__(self):
+                self.stdout = os.popen(pager, 'w')
+    else:
+        class Pager(BasePager):
+            def __init__(self):
+                self.pipe = Popen(pager, shell=True, stdin=PIPE,
+                                  universal_newlines=True)
+                self.stdout = self.pipe.stdin
+
+            def close(self):
+                BasePager.close(self)
+                self.pipe.wait()
+
+    def displayhook(value):
+        if value is not None:
+            builtins._ = value
+        pager = Pager()
+        try:
+            pager.pprint(value)
+        except:  # noqa
+            pager.stdout = ColoredFile(pager.stdout, '\033[31m')  # red
+            print_exc(file=pager)
+        pager.close()
+
+    sys.displayhook = displayhook
+
+    def excepthook(etype, evalue, etraceback):
+        lines = format_exception(etype, evalue, etraceback)
+        pager = Pager()
+        pager.stdout = ColoredFile(pager.stdout, '\033[31m')  # red
+        for line in lines:
+            pager.write(line)
+        pager.close()
+
+    sys.excepthook = excepthook
+
+    # try:
+    #     import cgitb
+    # except ImportError:
+    #     pass
+    # else:
+    #     # cgitb.enable() overrides sys.excepthook
+    #     cgitb.enable(format='text')
+
+    # 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:
     # https://mail.python.org/pipermail/python-list/2001-March/086191.html
@@ -151,20 +274,10 @@ def init():
             path = os.path.expanduser(os.path.expandvars(path or '~'))
             os.chdir(path)
 
-    __builtin__.ls = DirLister()
-    __builtin__.cd = DirChanger()
-
-    # From Thomas Heller:
-    # https://mail.python.org/pipermail/python-list/2001-April/099020.html
-
-    # From Thomas Heller
-    #
-    #import pdb
-    #
-    #def info(*args):
-    #   pdb.pm()
-    #sys.excepthook = info
+    builtins.ls = DirLister()
+    builtins.cd = DirChanger()
 
+    # print working directory
 
     class Pwd:
         def __repr__(self):
@@ -173,8 +286,9 @@ def init():
         def __call__(self):
             return repr(self)
 
-    __builtin__.pwd = Pwd()
+    builtins.pwd = Pwd()
 
+    # exit REPL with 'exit', 'quit' or simple 'x'
 
     class _Exit:
         def __repr__(self):
@@ -183,11 +297,9 @@ def init():
         def __call__(self, msg=None):
             sys.exit(msg)
 
-    __builtin__.x = _Exit()
-
-    if isinstance(__builtin__.exit, str): # In Python 2.5+ exit and quit are objects
-        __builtin__.exit = __builtin__.quit = x
+    builtins.x = _Exit()
 
+    # print conten of a file
 
     class _Cat:
         def __repr__(self):
@@ -197,10 +309,11 @@ def init():
             fp = open(filename, 'rU')
             text = fp.read()
             fp.close()
-            print text
+            print(text)
 
-    __builtin__.cat = _Cat()
+    builtins.cat = _Cat()
 
+    # call shell
 
     class _Sh:
         def __repr__(self):
@@ -210,29 +323,31 @@ def init():
         def __call__(self, cmdline):
             os.system(cmdline)
 
-    __builtin__.sh = _Sh()
+    builtins.sh = _Sh()
 
+    # paginate a file
 
     class _Pager:
         def __repr__(self):
             return "Usage: pager('filename')"
 
         def __call__(self, filename):
-            pager = os.environ.get("PAGER") or 'more'
             os.system("%s '%s'" % (pager, filename.replace("'", '"\'"')))
 
-    __builtin__.pager = _Pager()
+    builtins.pager = _Pager()
 
+    # edit a file
 
     class _Editor:
         def __repr__(self):
             return "Usage: edit('filename')"
 
         def __call__(self, filename):
-            editor = os.environ.get("VISUAL") or os.environ.get("EDITOR") or 'vi'
+            editor = os.environ.get("VISUAL") \
+                or os.environ.get("EDITOR") or 'vi'
             os.system("%s '%s'" % (editor, filename.replace("'", '"\'"')))
 
-    __builtin__.edit = __builtin__.editor = _Editor()
+    builtins.edit = builtins.editor = _Editor()
 
 
 init()