]> git.phdru.name Git - dotfiles.git/blob - lib/python/init.py
init.py: restore links to the origin of borrowed code
[dotfiles.git] / lib / python / init.py
1 # This is startup file for interactive python.
2 # It is not automatically loaded by python interpreter.
3 # To instruct the interpreter to load it insert the following commands
4 # into your .profile (use whatever syntax and initialization file
5 # is appropriate for your shell):
6 #
7 # PYTHONSTARTUP=$HOME/init.py # or where you really put it
8 # export PYTHONSTARTUP
9
10 def init():
11     import sys, os
12     import __builtin__
13
14     pyreadlinew32_startup = os.path.join(sys.prefix,
15         'lib', 'site-packages', 'pyreadline', 'configuration', 'startup.py')
16
17     if os.path.exists(pyreadlinew32_startup):
18         execfile(pyreadlinew32_startup)
19
20     else:
21         # From Bruce Edge:
22         # https://mail.python.org/pipermail/python-list/2001-March/062888.html
23
24         try:
25             import rlcompleter, readline
26             initfile = os.environ.get('INPUTRC') or os.path.expanduser('~/.inputrc')
27             readline.read_init_file(initfile)
28
29             histfile = os.path.expanduser('~/.python-history')
30             try:
31                 readline.read_history_file(histfile)
32             except IOError:
33                 pass # No such file
34
35             def savehist():
36                 histfilesize = os.environ.get('HISTFILESIZE') or \
37                                os.environ.get('HISTSIZE')
38                 if histfilesize:
39                     try:
40                         histfilesize = int(histfilesize)
41                     except ValueError:
42                         pass
43                     else:
44                         readline.set_history_length(histfilesize)
45                 readline.write_history_file(histfile)
46
47             import atexit
48             atexit.register(savehist)
49
50         except (ImportError, AttributeError):
51             pass # no readline or atexit, or readline doesn't have
52                  # {read,write}_history_file - ignore the error
53
54
55     term = os.environ.get('TERM', '')
56     if 'linux' in term:
57         background = 'dark'
58     else:
59         background = os.environ.get('BACKGROUND', 'light').lower()
60
61     # From Randall Hopper:
62     # https://mail.python.org/pipermail/python-list/2001-March/112696.html
63
64     for _term in ['linux', 'rxvt', 'screen', 'term', 'vt100']:
65         if _term not in term:
66             continue
67
68         if background == 'dark':
69             ps1_color = '3' # yellow
70             stdout_color = '7' # bold white
71         else:
72             ps1_color = '4' # blue
73             stdout_color = '0' # bold black
74
75         sys.ps1 = '\001\033[3%sm\002>>>\001\033[0m\002 ' % ps1_color
76         sys.ps2 = '\001\033[1;32m\002...\001\033[0m\002 ' # bold green
77
78
79         # From Denis Otkidach
80
81         class ColoredFile:
82             def __init__(self, fp, begin, end='\033[0m'): # reset all attributes
83                 self.__fp = fp
84                 self.__begin = begin
85                 self.__end = end
86
87             def write(self, s):
88                 self.__fp.write(self.__begin+s+self.__end)
89
90             def writelines(self, lines):
91                 map(self.write, lines)
92
93             def __getattr__(self, attr):
94                 return getattr(self.__fp, attr)
95
96         sys.stdout = ColoredFile(sys.stdout, '\033[1;3%sm' % stdout_color)
97         sys.stderr = ColoredFile(sys.stderr, '\033[31m') # red
98
99         break
100
101     try:
102         import locale
103     except ImportError:
104         pass # locale was not compiled
105     else:
106         try:
107             locale.setlocale(locale.LC_ALL, '')
108
109             from pprint import pprint
110
111             def displayhook(value):
112                 if value is not None:
113                     __builtin__._ = value
114                     pprint(value)
115
116             sys.displayhook = displayhook
117
118         except (ImportError, locale.Error):
119             pass # no locale support or unsupported locale
120
121
122     # From: Paul Magwene:
123     # https://mail.python.org/pipermail/python-list/2001-March/086191.html
124     # With a lot of my fixes:
125
126     class DirLister:
127         def __getitem__(self, key):
128             s = os.listdir(os.curdir)
129             return s[key]
130
131         def __getslice__(self, i, j):
132             s = os.listdir(os.curdir)
133             return s[i:j]
134
135         def __repr__(self):
136             return str(os.listdir(os.curdir))
137
138         def __call__(self, path=None):
139             if path:
140                 path = os.path.expanduser(os.path.expandvars(path))
141             else:
142                 path = os.curdir
143             return os.listdir(path)
144
145     class DirChanger:
146         def __repr__(self):
147             self()
148             return os.getcwd()
149
150         def __call__(self, path=None):
151             path = os.path.expanduser(os.path.expandvars(path or '~'))
152             os.chdir(path)
153
154     __builtin__.ls = DirLister()
155     __builtin__.cd = DirChanger()
156
157     # From Thomas Heller:
158     # https://mail.python.org/pipermail/python-list/2001-April/099020.html
159
160     # From Thomas Heller
161     #
162     #import pdb
163     #
164     #def info(*args):
165     #   pdb.pm()
166     #sys.excepthook = info
167
168
169     class Pwd:
170         def __repr__(self):
171             return os.getcwd()
172
173         def __call__(self):
174             return repr(self)
175
176     __builtin__.pwd = Pwd()
177
178
179     class _Exit:
180         def __repr__(self):
181             sys.exit()
182
183         def __call__(self, msg=None):
184             sys.exit(msg)
185
186     __builtin__.x = _Exit()
187
188     if isinstance(__builtin__.exit, str): # In Python 2.5+ exit and quit are objects
189         __builtin__.exit = __builtin__.quit = x
190
191
192     class _Cat:
193         def __repr__(self):
194             return "Usage: cat('filename')"
195
196         def __call__(self, filename):
197             fp = open(filename, 'rU')
198             text = fp.read()
199             fp.close()
200             print text
201
202     __builtin__.cat = _Cat()
203
204
205     class _Sh:
206         def __repr__(self):
207             os.system(os.environ["SHELL"])
208             return ''
209
210         def __call__(self, cmdline):
211             os.system(cmdline)
212
213     __builtin__.sh = _Sh()
214
215
216     class _Pager:
217         def __repr__(self):
218             return "Usage: pager('filename')"
219
220         def __call__(self, filename):
221             pager = os.environ.get("PAGER") or 'more'
222             os.system("%s '%s'" % (pager, filename.replace("'", '"\'"')))
223
224     __builtin__.pager = _Pager()
225
226
227     class _Editor:
228         def __repr__(self):
229             return "Usage: edit('filename')"
230
231         def __call__(self, filename):
232             editor = os.environ.get("VISUAL") or os.environ.get("EDITOR") or 'vi'
233             os.system("%s '%s'" % (editor, filename.replace("'", '"\'"')))
234
235     __builtin__.edit = __builtin__.editor = _Editor()
236
237
238 init()
239 del init