daily pastebin goal
68%
SHARE
TWEET

Untitled

a guest Jan 24th, 2018 52 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. """REPL enhancements for Python interactive interpreter.
  2.  
  3. This module adds:
  4.  
  5.  - tab completion (requires readline support)
  6.  - command history between sessions
  7.  - syntactic sugar for 'help(stmt)' via 'stmt?'
  8.  - user 'more' as pager command
  9.  - output history
  10.  
  11. To enable set the environment variables:
  12.  
  13.     PYTHONSTARTUP=$HOME/.startup.py
  14.  
  15. Note: The PYTHONSTARTUP environment variable wont expand a '~' to the users
  16. home directory, use $HOME instead.
  17. """
  18. try:
  19.     import atexit
  20.     import os
  21.     import readline
  22.     import rlcompleter
  23. except ImportError as err:
  24.     pass
  25. else:
  26.     class __ReadlineCompleter(rlcompleter.Completer):
  27.         """Tab completion support for readline.
  28.  
  29.         If there is not text for command completion, insert 4 spaces.
  30.         """
  31.  
  32.         def __init__(self, tab='    '):
  33.             self._complete = rlcompleter.Completer.complete
  34.             self._insert_text = readline.insert_text
  35.             self.tab = tab
  36.             rlcompleter.Completer.__init__(self)
  37.  
  38.         def complete(self, text, state):
  39.             if text == '':
  40.                 self.insert_text(self.tab)
  41.                 return None
  42.             else:
  43.                 return self._complete(self, text, state)
  44.  
  45.     readline.parse_and_bind('tab: complete')
  46.     readline.set_completer(__ReadlineCompleter().complete)
  47.  
  48.     class __HistoryManager(object):
  49.         """Load and store command history.
  50.  
  51.         Commands are persisted in file '~/.history.py'.
  52.         """
  53.  
  54.         def __init__(self, path='~/.history.py'):
  55.             self.history_path = os.path.expanduser(path)
  56.             self._read_history_file = readline.read_history_file
  57.             self._write_history_file = readline.write_history_file
  58.             self.load_history()
  59.  
  60.         def load_history(self):
  61.             if os.path.isfile(self.history_path):
  62.                 self._read_history_file(self.history_path)
  63.  
  64.         def save_history(self):
  65.             self._write_history_file(self.history_path)
  66.  
  67.     atexit.register(__HistoryManager().save_history)
  68.  
  69.     del __ReadlineCompleter
  70.     del __HistoryManager
  71.     del atexit, os, readline, rlcompleter
  72.  
  73.  
  74. try:
  75.     import inspect
  76.     import string
  77.     import sys
  78. except ImportError as err:
  79.     pass
  80. else:
  81.     class __HelpSyntax(object):
  82.         """Quick access to help documentation.
  83.  
  84.         If statement ends with a '?', evaulate help(stmt).
  85.         """
  86.  
  87.         def __init__(self):
  88.             self.default = sys.__excepthook__
  89.             self.isframe = inspect.isframe
  90.             self.stack = inspect.stack
  91.             self.stdout = sys.stdout
  92.             self.whitespace = string.whitespace
  93.  
  94.         def __call__(self, type, value, traceback):
  95.             if not isinstance(value, SyntaxError):
  96.                 return self.default(type, value, traceback)
  97.             stmt = value.text.rstrip()
  98.             if not stmt.endswith('?'):
  99.                 return self.default(type, value, traceback)
  100.             name = stmt.rstrip('?(' + self.whitespace)
  101.             self.show_help(name)
  102.  
  103.         def show_help(self, name):
  104.             for record in self.stack():
  105.                 frame = record[0]
  106.                 if not self.isframe(frame):
  107.                     continue
  108.                 if frame.f_globals.get('__name__') != '__main__':
  109.                     continue
  110.                 cmd = 'help({0})'.format(name)
  111.                 self.stdout.write(cmd)
  112.                 return eval(cmd, frame.f_globals, frame.f_locals)
  113.  
  114.     sys.excepthook = __HelpSyntax()
  115.  
  116.     del __HelpSyntax
  117.     del inspect, string, sys
  118.  
  119.  
  120. try:
  121.     import functools
  122.     import pydoc
  123. except ImportError as err:
  124.     pass
  125. else:
  126.     pydoc.pager = functools.partial(pydoc.pipepager, cmd='more')
  127.  
  128.     del functools, pydoc
  129.  
  130.  
  131. try:
  132.     import sys
  133. except ImportError as err:
  134.     pass
  135. else:
  136.     class __Prompt(object):
  137.         """Maintain dictionary of output history.
  138.  
  139.         If '__history__' is a dict, store output results using one up number
  140.         keys. Prompt is changed to identify how many keys have been populated.
  141.         """
  142.  
  143.         def __init__(self, prompt='>>> '):
  144.             self.counter = 0
  145.             self.prompt = prompt
  146.  
  147.         def __radd__(self, left):
  148.             return str(left) + str(self)
  149.  
  150.         def __str__(self):
  151.             if self.is_history():
  152.                 self.update_history()
  153.                 return 'H[{0}] {1}'.format(self.counter, self.prompt)
  154.             return self.prompt
  155.  
  156.         def is_history(self):
  157.             return isinstance(globals().get('__history__'), dict)
  158.  
  159.         def update_history(self):
  160.             try:
  161.                 if (_ is not __history__ and
  162.                         _ is not __history__.get(self.counter)):
  163.                     self.counter += 1
  164.                     __history__[self.counter] = _
  165.                     return True
  166.             except NameError:
  167.                 pass
  168.             finally:
  169.                 return True
  170.  
  171.     # __history__ = {0: None}
  172.     __history__ = None
  173.     sys.ps1 = __Prompt()
  174.  
  175.     del __Prompt
  176.     del sys
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top