# vim: ft=python # original at # https://raw.githubusercontent.com/whiteinge/dotfiles/master/.pythonrc.py from __future__ import print_function from __future__ import unicode_literals from __future__ import absolute_import from __future__ import division del print_function del unicode_literals del absolute_import del division import itertools import functools import collections import sys import os import pprint try: import setproctitle setproctitle.setproctitle("{}.shell".format(os.path.basename(os.environ['VIRTUAL_ENV']))) del setproctitle except ImportError as exc: # WE DON'T CARE pass import datetime import time import codeop import dis import pdb import traceback import inspect import cProfile import timeit import pstats import importlib from tempfile import mkstemp class TermColors(dict): """Gives easy access to ANSI color codes. Attempts to fall back to no color for certain TERM values. (Mostly stolen from IPython.)""" COLOR_TEMPLATES = ( ("Black", "0;30"), ("Red", "0;31"), ("Green", "0;32"), ("Brown", "0;33"), ("Blue", "0;34"), ("Purple", "0;35"), ("Cyan", "0;36"), ("LightGray", "0;37"), ("DarkGray", "1;30"), ("LightRed", "1;31"), ("LightGreen", "1;32"), ("Yellow", "1;33"), ("LightBlue", "1;34"), ("LightPurple", "1;35"), ("LightCyan", "1;36"), ("White", "1;37"), ("Normal", "0"), ) NoColor = '' _base = '\001\033[%sm\002' def __init__(self): if os.environ.get('TERM') in ('xterm-color', 'xterm-256color', 'linux', 'screen', 'screen-256color', 'screen-bce'): self.update( dict( [(k, self._base % v) for k, v in self.COLOR_TEMPLATES] ) ) else: self.update( dict( [(k, self.NoColor) for k, v in self.COLOR_TEMPLATES] ) ) _c = TermColors() # Enable Color Prompts ###################### sys.ps1 = '%s>>> %s' % (_c['Green'], _c['Normal']) sys.ps2 = '%s... %s' % (_c['Blue'], _c['Normal']) del _c del TermColors def my_displayhook(value): """Enable Pretty Printing for stdout.""" if value is not None: try: import __builtin__ __builtin__._ = value except ImportError: __builtins__._ = value pprint.pprint(value) sys.displayhook = my_displayhook del my_displayhook HISTFILE = "{}/.pyhistory".format(os.environ["HOME"]) try: import readline except ImportError: # print("Module readline not available.") has_readline = False else: has_readline = True # import rlcompleter # if 'libedit' in readline.__doc__: # readline.parse_and_bind("bind ^I rl_complete") # else: # readline.parse_and_bind("tab: complete") try: # Read the existing history if there is one if os.path.exists(HISTFILE): readline.read_history_file(HISTFILE) # Set maximum number of items that will be written to the history file readline.set_history_length(9999) def savehist(): import readline readline.write_history_file(HISTFILE) import atexit atexit.register(savehist) del savehist del atexit except NameError: # no readline? pass # del rlcompleter # del HISTFILE # Start an external editor with \e ################################## # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/438813/ import code class EditableBufferInteractiveConsole(code.InteractiveConsole): # http://matplotlib.org/1.4.0/examples/user_interfaces/interactive.html def __init__(self, *args, **kwargs): self.EDITOR = os.environ.get('EDITOR', 'vi') # TODO: make this read and run whatever file # TODO: make \e and \o dump the stuff you type into the HISTFILE self.NEW_CMD = '\o' self.EDIT_CMD = '\e' self.last_buffer = [] # This holds the last executed statement code.InteractiveConsole.__init__(self, *args, **kwargs) self.runsource_old = code.InteractiveConsole.runsource self.raw_input_old = code.InteractiveConsole.raw_input self.mkstemp = mkstemp if has_readline: import rlcompleter try: self.completer = rlcompleter.Completer(self.locals) except: self.completer = rlcompleter.Completer() readline.set_completer(self.completer.complete) readline.parse_and_bind('tab: complete') # This forces readline to automatically print the above list when tab # completion is set to 'complete'. readline.parse_and_bind('set show-all-if-ambiguous on') # Bindings for incremental searches in the history. These searches # use the string typed so far on the command line and search # anything in the previous input history containing them. readline.parse_and_bind('"\C-r": reverse-search-history') readline.parse_and_bind('"\C-s": forward-search-history') def runsource(self, source, *args): if source == '': return False self.last_buffer = [source.encode('utf-8')] return self.runsource_old(self, source, *args) def raw_input(self, *args): line = self.raw_input_old(self, *args) # if line == self.EDIT_CMD: if line.startswith(self.EDIT_CMD): words = line.split(' ')[1:] num_params = len(words) if num_params > 1: print('\e command takes at most one parameter') # raise SyntaxError('\e command takes at most one parameter') elif num_params == 1: filename = words[0] filename = filename.replace('~', os.environ['HOME']) filename = os.path.realpath(filename) os.system('%s %s' % (self.EDITOR, filename)) try: line = open(filename).read() except IOError: traceback.print_exc() return '' try: exec(line, globals(), self.locals) except SyntaxError: traceback.print_exc() return '' # lines = line.splitlines() # map(lambda push_line: self.push(push_line), lines) self.last_buffer = [line] line = '' else: fd, tmpfl = self.mkstemp('.py') os.write(fd, b'\n'.join(self.last_buffer)) os.close(fd) os.system('%s %s' % (self.EDITOR, tmpfl)) line = open(tmpfl).read() os.unlink(tmpfl) tmpfl = '' try: exec(line, globals(), self.locals) except SyntaxError: traceback.print_exc() return '' # lines = line.splitlines() # map(lambda push_line: self.push(push_line), lines) self.last_buffer = [line] line = '' elif line == self.NEW_CMD: fd, tmpfl = self.mkstemp('.py') os.system('%s %s' % (self.EDITOR, tmpfl)) line = open(tmpfl).read() os.unlink(tmpfl) tmpfl = '' try: exec(line, globals(), self.locals) except SyntaxError: traceback.print_exc() return '' # lines = line.splitlines() # map(lambda push_line: self.push(push_line), lines) self.last_buffer = [line] line = '' return line sys.path.insert(0, '.') try: get_ipython del EditableBufferInteractiveConsole del code del mkstemp del readline del has_readline except NameError: import copy c = EditableBufferInteractiveConsole(locals=copy.copy(locals())) del copy future_lines = [ 'from __future__ import print_function', 'from __future__ import unicode_literals', 'from __future__ import absolute_import', 'from __future__ import division', 'del print_function', 'del unicode_literals', 'del absolute_import', 'del division', ] list([c.push(line) for line in future_lines]) c.push('del EditableBufferInteractiveConsole') c.push('del code') c.push('del HISTFILE') c.push('del __file__') c.push('del mkstemp') c.push('del has_readline') # c.push('del __package__') # c.push('del __doc__') c.push(""" try: del readline except: pass """) c.push('sys.argv = sys.argv[2:]') c.last_buffer = [''] c.interact(banner="") # Exit the Python shell on exiting the InteractiveConsole sys.exit()