]> git.phdru.name Git - dotfiles.git/blob - lib/python/init.py
init.py: use pager to view a (possibly quite long) traceback
[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
11 def init():
12     import __builtin__
13     import os
14     import sys
15
16     # readline/pyreadline
17
18     pyreadlinew32_startup = os.path.join(
19         sys.prefix, 'lib', 'site-packages',
20         'pyreadline', 'configuration', 'startup.py')
21
22     if os.path.exists(pyreadlinew32_startup):
23         execfile(pyreadlinew32_startup)
24
25     else:
26         # From Bruce Edge:
27         # https://mail.python.org/pipermail/python-list/2001-March/062888.html
28
29         try:
30             import rlcompleter  # noqa: need for completion
31             import readline
32             initfile = os.environ.get('INPUTRC') \
33                 or os.path.expanduser('~/.inputrc')
34             readline.read_init_file(initfile)
35
36             histfile = os.path.expanduser('~/.python-history')
37             try:
38                 readline.read_history_file(histfile)
39             except IOError:
40                 pass  # No such file
41
42             def savehist():
43                 histfilesize = os.environ.get('HISTFILESIZE') \
44                     or os.environ.get('HISTSIZE')
45                 if histfilesize:
46                     try:
47                         histfilesize = int(histfilesize)
48                     except ValueError:
49                         pass
50                     else:
51                         readline.set_history_length(histfilesize)
52                 readline.write_history_file(histfile)
53
54             import atexit
55             atexit.register(savehist)
56
57         except (ImportError, AttributeError):
58             # no readline or atexit, or readline doesn't have
59             # {read,write}_history_file - ignore the error
60             pass
61
62     # terminal
63
64     term = os.environ.get('TERM', '')
65     if 'linux' in term:
66         background = 'dark'
67     else:
68         background = os.environ.get('BACKGROUND', 'light').lower()
69
70     # From Randall Hopper:
71     # https://mail.python.org/pipermail/python-list/2001-March/112696.html
72
73     for _term in ['linux', 'rxvt', 'screen', 'term', 'vt100']:
74         if _term not in term:
75             continue
76
77         if background == 'dark':
78             ps1_color = '3'  # yellow
79             stdout_color = '7'  # bold white
80         else:
81             ps1_color = '4'  # blue
82             stdout_color = '0'  # bold black
83
84         sys.ps1 = '\001\033[3%sm\002>>>\001\033[0m\002 ' % ps1_color
85         sys.ps2 = '\001\033[1;32m\002...\001\033[0m\002 '  # bold green
86
87         # From Denis Otkidach
88
89         class ColoredFile:
90             def __init__(self, fp, begin,
91                          end='\033[0m'):  # reset all attributes
92                 self.__fp = fp
93                 self.__begin = begin
94                 self.__end = end
95
96             def write(self, s):
97                 self.__fp.write(self.__begin+s+self.__end)
98
99             def writelines(self, lines):
100                 map(self.write, lines)
101
102             def __getattr__(self, attr):
103                 return getattr(self.__fp, attr)
104
105         sys.stdout = ColoredFile(sys.stdout, '\033[1;3%sm' % stdout_color)
106         sys.stderr = ColoredFile(sys.stderr, '\033[31m')  # red
107
108         break
109
110     try:
111         import locale
112     except ImportError:
113         pass  # locale was not compiled
114     else:
115         try:
116             locale.setlocale(locale.LC_ALL, '')
117
118         except (ImportError, locale.Error):
119             pass  # no locale support or unsupported locale
120
121     # set displayhook
122
123     from pprint import pprint
124
125     class BasePPrintPager:
126         def pipe(self, value):
127             pprint(value, stream=self.stdin)
128
129         def close(self):
130             self.stdin.close()
131
132     try:
133         from subprocess import Popen, PIPE
134     except ImportError:
135         class PPrintPager(BasePPrintPager):
136             def __init__(self):
137                 self.pipe = Popen(pager, shell=True, stdin=PIPE)
138                 self.stdin = self.pipe.stdin
139
140             def close(self):
141                 BasePPrintPager.close(self)
142                 self.pipe.wait()
143     else:
144         class PPrintPager(BasePPrintPager):
145             def __init__(self):
146                 self.stdin = os.popen(pager, 'w')
147     pager = os.environ.get("PAGER") or 'more'
148
149     def displayhook(value):
150         if value is not None:
151             __builtin__._ = value
152         pprint_pager = PPrintPager()
153         pprint_pager.pipe(value)
154         pprint_pager.close()
155
156     sys.displayhook = displayhook
157
158     from traceback import print_exception
159
160     def excepthook(etype, evalue, etraceback):
161         pprint_pager = PPrintPager()
162         print_exception(etype, evalue, etraceback, file=pprint_pager.stdin)
163         pprint_pager.close()
164
165     sys.excepthook = excepthook
166
167     # From Thomas Heller:
168     # https://mail.python.org/pipermail/python-list/2001-April/099020.html
169
170     # import pdb
171     #
172     # def info(*args):
173     #    pdb.pm()
174     # sys.excepthook = info
175
176     # utilities
177
178     # From: Paul Magwene:
179     # https://mail.python.org/pipermail/python-list/2001-March/086191.html
180     # With a lot of my fixes:
181
182     class DirLister:
183         def __getitem__(self, key):
184             s = os.listdir(os.curdir)
185             return s[key]
186
187         def __getslice__(self, i, j):
188             s = os.listdir(os.curdir)
189             return s[i:j]
190
191         def __repr__(self):
192             return str(os.listdir(os.curdir))
193
194         def __call__(self, path=None):
195             if path:
196                 path = os.path.expanduser(os.path.expandvars(path))
197             else:
198                 path = os.curdir
199             return os.listdir(path)
200
201     class DirChanger:
202         def __repr__(self):
203             self()
204             return os.getcwd()
205
206         def __call__(self, path=None):
207             path = os.path.expanduser(os.path.expandvars(path or '~'))
208             os.chdir(path)
209
210     __builtin__.ls = DirLister()
211     __builtin__.cd = DirChanger()
212
213     # print working directory
214
215     class Pwd:
216         def __repr__(self):
217             return os.getcwd()
218
219         def __call__(self):
220             return repr(self)
221
222     __builtin__.pwd = Pwd()
223
224     # exit REPL with 'exit', 'quit' or simple 'x'
225
226     class _Exit:
227         def __repr__(self):
228             sys.exit()
229
230         def __call__(self, msg=None):
231             sys.exit(msg)
232
233     __builtin__.x = _Exit()
234
235     # In Python 2.5+ exit and quit are objects
236     if isinstance(__builtin__.exit, str):
237         __builtin__.exit = __builtin__.quit = x  # noqa: x is defined as _Exit
238
239     # print conten of a file
240
241     class _Cat:
242         def __repr__(self):
243             return "Usage: cat('filename')"
244
245         def __call__(self, filename):
246             fp = open(filename, 'rU')
247             text = fp.read()
248             fp.close()
249             print text
250
251     __builtin__.cat = _Cat()
252
253     # call shell
254
255     class _Sh:
256         def __repr__(self):
257             os.system(os.environ["SHELL"])
258             return ''
259
260         def __call__(self, cmdline):
261             os.system(cmdline)
262
263     __builtin__.sh = _Sh()
264
265     # paginate a file
266
267     class _Pager:
268         def __repr__(self):
269             return "Usage: pager('filename')"
270
271         def __call__(self, filename):
272             os.system("%s '%s'" % (pager, filename.replace("'", '"\'"')))
273
274     __builtin__.pager = _Pager()
275
276     # edit a file
277
278     class _Editor:
279         def __repr__(self):
280             return "Usage: edit('filename')"
281
282         def __call__(self, filename):
283             editor = os.environ.get("VISUAL") \
284                 or os.environ.get("EDITOR") or 'vi'
285             os.system("%s '%s'" % (editor, filename.replace("'", '"\'"')))
286
287     __builtin__.edit = __builtin__.editor = _Editor()
288
289
290 init()
291 del init