Last active
December 18, 2015 01:59
-
-
Save davesque/5708169 to your computer and use it in GitHub Desktop.
Cleaned up .pythonrc.py file
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from code import InteractiveConsole | |
import os | |
import sys | |
completer_locals = locals() | |
HISTFILE = os.path.expanduser("%s/.pyhistory" % os.environ["HOME"]) | |
################# | |
##| |## | |
##| Utilities |## | |
##| |## | |
################# | |
class ReadLine(object): | |
""" | |
Enables readline functionality in the python shell. | |
""" | |
def __init__(self): | |
global HISTFILE | |
global completer_locals | |
self._histfile = HISTFILE | |
try: | |
import readline | |
import rlcompleter | |
import atexit | |
readline.parse_and_bind("tab: complete") | |
#readline.parse_and_bind("bind ^I rl_complete") # For OSX | |
# Read the existing history if there is one | |
if os.path.exists(self._histfile): | |
readline.read_history_file(self._histfile) | |
# Configure readline | |
readline.set_history_length(300) | |
readline.set_completer(rlcompleter.Completer(completer_locals).complete) | |
atexit.register(self.savehist) | |
except ImportError: | |
print("You need readline, rlcompleter, and atexit") | |
def savehist(self): | |
import readline | |
readline.write_history_file(self._histfile) | |
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.) | |
""" | |
TERMS = ( | |
'xterm-color', | |
'xterm-256color', | |
'linux', | |
'screen', | |
'screen-256color', | |
'screen-bce', | |
) | |
NO_COLOR = '' | |
BASE = '\001\033[{0}m\002' | |
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"), | |
) | |
def __init__(self): | |
if os.environ.get('TERM') in self.TERMS: | |
self.update(dict([(k, self.BASE.format(v)) for k, v in self.COLOR_TEMPLATES])) | |
else: | |
self.update(dict([(k, self.NO_COLOR) for k, v in self.COLOR_TEMPLATES])) | |
class DjangoModels(object): | |
""" | |
Gives easy access to django models. | |
""" | |
def __init__(self): | |
from django.db.models.loading import get_models | |
for m in get_models(): | |
setattr(self, m.__name__, m) | |
class EditableConsole(InteractiveConsole): | |
""" | |
Allows editing of console commands in $EDITOR. | |
""" | |
EDITOR = os.environ.get('EDITOR', 'vim') | |
EDIT_CMD = '\e' | |
def __init__(self, *args, **kwargs): | |
from code import InteractiveConsole | |
# Holds the last executed statement | |
self.last_buffer = [] | |
InteractiveConsole.__init__(self, *args, **kwargs) | |
def runsource(self, source, *args): | |
from code import InteractiveConsole | |
self.last_buffer = [source.encode('latin-1')] | |
return InteractiveConsole.runsource(self, source, *args) | |
def raw_input(self, *args): | |
from code import InteractiveConsole | |
from tempfile import mkstemp | |
line = InteractiveConsole.raw_input(self, *args) | |
if line == self.EDIT_CMD: | |
# Make temporary file | |
fd, tmpfile = mkstemp('.py') | |
# Write last statement to file | |
os.write(fd, b'\n'.join(self.last_buffer)) | |
os.close(fd) | |
# Edit file in editor | |
os.system('{0} {1}'.format(self.EDITOR, tmpfile)) | |
# Get edited statement | |
line = open(tmpfile).read() | |
os.remove(tmpfile) | |
# Push into readline history | |
try: | |
import readline | |
readline.add_history(line) | |
except ImportError: | |
pass | |
return line | |
def history(enum=False): | |
""" | |
Displays the command history. | |
""" | |
global HISTFILE | |
import sys | |
if os.path.exists(HISTFILE): | |
with open(HISTFILE, 'r') as f: | |
if enum: | |
for i, l in enumerate(f.readlines()): | |
sys.stdout.write('{0} {1}'.format(i, l)) | |
else: | |
for l in f.readlines(): | |
sys.stdout.write(l) | |
def secret_key(): | |
""" | |
Generates a new SECRET_KEY that can be used in a project settings file. | |
""" | |
from random import choice | |
return ''.join([ | |
choice('abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)') | |
for i in range(50) | |
]) | |
def my_displayhook(value): | |
""" | |
Adds the previous value as a variable and pretty prints any values which | |
are output in the console. | |
""" | |
if value is not None: | |
try: | |
import __builtin__ | |
__builtin__._ = value | |
except ImportError: | |
__builtins__._ = value | |
import pprint | |
pprint.pprint(value) | |
del pprint | |
############### | |
##| |## | |
##| Startup |## | |
##| |## | |
############### | |
read_line = ReadLine() | |
colors = TermColors() | |
sys.ps1 = '{green}>>> {normal}'.format(**colors) | |
sys.ps2 = '{red}... {normal}'.format(**colors) | |
sys.displayhook = my_displayhook | |
# If in a Django shell, set up some conveniences for Django | |
if 'DJANGO_SETTINGS_MODULE' in os.environ: | |
from django.test.client import Client | |
from django.test.utils import setup_test_environment | |
from django.conf import settings as S | |
A = DjangoModels() | |
C = Client() | |
welcome_msg = ( | |
'{green}Django environment detected.\n' | |
'\n' | |
'* Your project settings are available as `S`.\n' | |
'* Your INSTALLED_APPS models are available as `A`.\n' | |
'* The Django test client is available as `C`.\n' | |
'{normal}'.format(**colors) | |
) | |
setup_test_environment() | |
S.DEBUG_PROPAGATE_EXCEPTIONS = True | |
welcome_msg += ( | |
'{lightpurple}\n' | |
'Warning: The Django test environment has been set up. To restore the\n' | |
'normal environment, call `teardown_test_environment()`.\n' | |
'\n' | |
'Warning: DEBUG_PROPAGATE_EXCEPTIONS has been set to True.\n' | |
'{normal}'.format(**colors) | |
) | |
else: | |
welcome_msg = '' | |
# Clean up namespace | |
del sys | |
# Start the interactive console | |
console = EditableConsole(locals=completer_locals) | |
console.interact(banner=welcome_msg) | |
# Exit shell after exiting interactive console | |
import sys | |
sys.exit() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment