Guest User

.pythonrc

a guest
Aug 11th, 2011
152
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 5.56 KB | None | 0 0
  1. """
  2. This file is executed when the Python interactive shell is started if
  3. $PYTHONSTARTUP is in your environment and points to this file. It's just
  4. regular Python commands, so do what you will. Your ~/.inputrc file can greatly
  5. complement this file.
  6.  
  7. """
  8. import os
  9.  
  10. try:
  11. import readline
  12. import rlcompleter
  13. import atexit
  14. except ImportError:
  15. print("You need readline, rlcompleter, and atexit")
  16.  
  17. readline.parse_and_bind("tab: complete")
  18. readline.parse_and_bind ("bind ^I rl_complete")
  19.  
  20. class Completer(object):
  21. def __init__(self):
  22. # Enable a History
  23. self.HISTFILE=os.path.expanduser("%s/.pyhistory" % os.environ["HOME"])
  24.  
  25. # Read the existing history if there is one
  26. if os.path.exists(self.HISTFILE):
  27. readline.read_history_file(self.HISTFILE)
  28.  
  29. # Set maximum number of items that will be written to the history file
  30. readline.set_history_length(300)
  31. atexit.register(self.savehist)
  32.  
  33. def savehist(self):
  34. import readline
  35. readline.write_history_file(self.HISTFILE)
  36.  
  37.  
  38. c = Completer()
  39.  
  40. WELCOME=''
  41. # Color Support
  42. class TermColors(dict):
  43. """Gives easy access to ANSI color codes. Attempts to fall back to no color
  44. for certain TERM values. (Mostly stolen from IPython.)"""
  45.  
  46. COLOR_TEMPLATES = (
  47. ("Black" , "0;30"),
  48. ("Red" , "0;31"),
  49. ("Green" , "0;32"),
  50. ("Brown" , "0;33"),
  51. ("Blue" , "0;34"),
  52. ("Purple" , "0;35"),
  53. ("Cyan" , "0;36"),
  54. ("LightGray" , "0;37"),
  55. ("DarkGray" , "1;30"), ("LightRed" , "1;31"),
  56. ("LightGreen" , "1;32"),
  57. ("Yellow" , "1;33"),
  58. ("LightBlue" , "1;34"),
  59. ("LightPurple" , "1;35"),
  60. ("LightCyan" , "1;36"),
  61. ("White" , "1;37"),
  62. ("Normal" , "0"),
  63. )
  64.  
  65. NoColor = ''
  66. _base = '\001\033[%sm\002'
  67.  
  68. def __init__(self):
  69. if os.environ.get('TERM') in ('xterm-color', 'xterm-256color', 'linux',
  70. 'screen', 'screen-256color', 'screen-bce'):
  71. self.update(dict([(k, self._base % v) for k,v in self.COLOR_TEMPLATES]))
  72. else:
  73. self.update(dict([(k, self.NoColor) for k,v in self.COLOR_TEMPLATES]))
  74. _c = TermColors()
  75.  
  76.  
  77.  
  78. import sys
  79. # Enable Color Prompts
  80. sys.ps1 = '%s>>> %s' % (_c['Green'], _c['Normal'])
  81. sys.ps2 = '%s... %s' % (_c['Red'], _c['Normal'])
  82.  
  83. # Enable Pretty Printing for stdout
  84. def my_displayhook(value):
  85. if value is not None:
  86. try:
  87. import __builtin__
  88. __builtin__._ = value
  89. except ImportError:
  90. __builtins__._ = value
  91.  
  92. import pprint
  93. pprint.pprint(value)
  94. del pprint
  95.  
  96. sys.displayhook = my_displayhook
  97.  
  98. # Django Helpers
  99. def SECRET_KEY():
  100. "Generates a new SECRET_KEY that can be used in a project settings file."
  101.  
  102. from random import choice
  103. return ''.join(
  104. [choice('abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)')
  105. for i in range(50)])
  106.  
  107. # If we're working with a Django project, set up the environment
  108. if 'DJANGO_SETTINGS_MODULE' in os.environ:
  109. from django.db.models.loading import get_models
  110. from django.test.client import Client
  111. from django.test.utils import setup_test_environment, teardown_test_environment
  112. from django.conf import settings as S
  113. class DjangoModels(object):
  114. """Loop through all the models in INSTALLED_APPS and import them."""
  115. def __init__(self):
  116. for m in get_models():
  117. setattr(self, m.__name__, m)
  118.  
  119. A = DjangoModels()
  120. C = Client()
  121.  
  122. WELCOME += """%(Green)s
  123. Django environment detected.
  124. * Your INSTALLED_APPS models are available as `A`.
  125. * Your project settings are available as `S`.
  126. * The Django test client is available as `C`.
  127. %(Normal)s""" % _c
  128.  
  129. setup_test_environment()
  130. S.DEBUG_PROPAGATE_EXCEPTIONS = True
  131.  
  132. WELCOME += """%(LightPurple)s
  133. Warning: the Django test environment has been set up; to restore the
  134. normal environment call `teardown_test_environment()`.
  135.  
  136. Warning: DEBUG_PROPAGATE_EXCEPTIONS has been set to True.
  137. %(Normal)s""" % _c
  138.  
  139. # Start an external editor with \e
  140. # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/438813/
  141.  
  142. EDITOR = os.environ.get('EDITOR', 'vim')
  143. EDIT_CMD = '\e'
  144.  
  145. from tempfile import mkstemp
  146. from code import InteractiveConsole
  147.  
  148. class EditableBufferInteractiveConsole(InteractiveConsole):
  149. def __init__(self, *args, **kwargs):
  150. self.last_buffer = [] # This holds the last executed statement
  151. InteractiveConsole.__init__(self, *args, **kwargs)
  152.  
  153. def runsource(self, source, *args):
  154. self.last_buffer = [ source.encode('latin-1') ]
  155. return InteractiveConsole.runsource(self, source, *args)
  156.  
  157. def raw_input(self, *args):
  158. line = InteractiveConsole.raw_input(self, *args)
  159. if line == EDIT_CMD:
  160. fd, tmpfl = mkstemp('.py')
  161. os.write(fd, b'\n'.join(self.last_buffer))
  162. os.close(fd)
  163. os.system('%s %s' % (EDITOR, tmpfl))
  164. line = open(tmpfl).read()
  165. os.unlink(tmpfl)
  166. tmpfl = ''
  167. lines = line.split( '\n' )
  168. for i in range(len(lines) - 1): self.push( lines[i] )
  169. line = lines[-1]
  170. return line
  171.  
  172. # clean up namespace
  173. del sys
  174.  
  175. c = EditableBufferInteractiveConsole(locals=locals())
  176. c.interact(banner=WELCOME)
  177.  
  178. # Exit the Python shell on exiting the InteractiveConsole
  179. import sys
  180. sys.exit()
Advertisement
Add Comment
Please, Sign In to add comment