]> git.phdru.name Git - dotfiles.git/blob - lib/python/init.py
init.py: Hide errors during `.write_history_file()`
[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     try:
13         import __builtin__ as builtins
14     except ImportError:
15         import builtins
16     import os
17     import sys
18
19     # readline/pyreadline
20
21     pyreadlinew32_startup = os.path.join(
22         sys.prefix, 'lib', 'site-packages',
23         'pyreadline', 'configuration', 'startup.py')
24
25     if os.path.exists(pyreadlinew32_startup):
26         execfile(pyreadlinew32_startup)
27
28     else:
29         # From Bruce Edge:
30         # https://mail.python.org/pipermail/python-list/2001-March/062888.html
31
32         try:
33             import rlcompleter  # noqa: need for completion
34             import readline
35             initfile = os.environ.get('INPUTRC') \
36                 or os.path.expanduser('~/.inputrc')
37             readline.read_init_file(initfile)
38
39             # if 'libedit' in readline.__doc__:
40             #     readline.parse_and_bind("bind ^I rl_complete")
41             # else:
42             #     readline.parse_and_bind("tab: complete")
43
44             histfiles = ['~/.python_history']
45             # if 'VIRTUAL_ENV' in os.environ:
46             #     histfiles.append('$VIRTUAL_ENV/.python_history')
47             for histfile in histfiles:
48                 try:
49                     histfile = os.path.expandvars(histfile)
50                     histfile = os.path.expanduser(histfile)
51                     readline.read_history_file(histfile)
52                 except IOError:
53                     pass  # No such file
54
55             def savehist():
56                 histsize = os.environ.get('HISTSIZE')
57                 if histsize:
58                     try:
59                         histsize = int(histsize)
60                     except ValueError:
61                         pass
62                     else:
63                         readline.set_history_length(histsize)
64                 histfile = histfiles[-1]
65                 histfile = os.path.expandvars(histfile)
66                 histfile = os.path.expanduser(histfile)
67                 try:
68                     readline.write_history_file(histfile)
69                 except IOError:
70                     pass
71
72             import atexit
73             atexit.register(savehist)
74
75         except (ImportError, AttributeError):
76             # no readline or atexit, or readline doesn't have
77             # {read,write}_history_file - ignore the error
78             pass
79
80     # terminal
81
82     term = os.environ.get('TERM', '')
83     if 'linux' in term:
84         background = 'dark'
85     else:
86         background = os.environ.get('BACKGROUND', 'light').lower()
87
88     # From Randall Hopper:
89     # https://mail.python.org/pipermail/python-list/2001-March/112696.html
90
91     _term_found = False
92     for _term in ['linux', 'rxvt', 'screen', 'term', 'vt100']:
93         if _term in term:
94             _term_found = True
95             break
96
97     if _term_found:
98         if background == 'dark':
99             ps1_color = '3'  # yellow
100             stdout_color = '7'  # bold white
101         else:
102             ps1_color = '4'  # blue
103             stdout_color = '0'  # bold black
104
105         sys.ps1 = '\001\033[3%sm\002>>>\001\033[0m\002 ' % ps1_color
106         sys.ps2 = '\001\033[1;32m\002...\001\033[0m\002 '  # bold green
107
108         # From Denis Otkidach
109
110         class ColoredFile:
111             def __init__(self, fp, begin,
112                          end='\033[0m'):  # reset all attributes
113                 self.__fp = fp
114                 self.__begin = begin
115                 self.__end = end
116
117             def write(self, s):
118                 self.__fp.write(self.__begin+s+self.__end)
119
120             def writelines(self, lines):
121                 map(self.write, lines)
122
123             def __getattr__(self, attr):
124                 return getattr(self.__fp, attr)
125
126         sys.stdout = ColoredFile(sys.stdout, '\033[1;3%sm' % stdout_color)
127         sys.stderr = ColoredFile(sys.stderr, '\033[31m')  # red
128
129         def myinput(prompt=None):
130             save_stdout = sys.stdout
131             sys.stdout = sys.__stdout__
132             try:
133                 result = builtin_input(prompt)
134             except EOFError:
135                 result = None
136             sys.stdout = save_stdout
137             return result
138
139         try:
140             builtins.raw_input
141         except AttributeError:  # PY3
142             builtin_input = builtins.input
143             builtins.input = myinput
144         else:
145             builtin_input = builtins.raw_input
146             builtins.raw_input = myinput
147
148     try:
149         import locale
150     except ImportError:
151         pass  # locale was not compiled
152     else:
153         try:
154             locale.setlocale(locale.LC_ALL, '')
155         except (ImportError, locale.Error):
156             pass  # no locale support or unsupported locale
157
158     # set displayhook and excepthook
159
160     from pprint import pprint
161     from traceback import format_exception, print_exc
162
163     pager = os.environ.get("PAGER") or 'more'
164
165     # if your pager is 'less', options '-F' and '-R' must be passed to it,
166     # and option '-X' is very much recommended
167     if pager == 'less':
168         less = os.environ.get("LESS") or ''
169         for opt in 'X', 'R', 'F':
170             if opt not in less:
171                 less = opt + less
172         os.environ["LESS"] = less
173
174     class BasePager:
175         def write(self, value):
176             self.stdout.write(value)
177
178         def pprint(self, value):
179             pprint(value,
180                    stream=ColoredFile(self.stdout,
181                                       '\033[1;3%sm' % stdout_color))
182
183         def close(self):
184             self.stdout.close()
185
186     try:
187         from subprocess import Popen, PIPE
188     except ImportError:
189         class Pager(BasePager):
190             def __init__(self):
191                 self.stdout = os.popen(pager, 'w')
192     else:
193         class Pager(BasePager):
194             def __init__(self):
195                 self.pipe = Popen(pager, shell=True, stdin=PIPE,
196                                   universal_newlines=True)
197                 self.stdout = self.pipe.stdin
198
199             def close(self):
200                 BasePager.close(self)
201                 self.pipe.wait()
202
203     def displayhook(value):
204         if value is not None:
205             builtins._ = value
206         pager = Pager()
207         try:
208             pager.pprint(value)
209         except:  # noqa
210             pager.stdout = ColoredFile(pager.stdout, '\033[31m')  # red
211             print_exc(file=pager)
212         pager.close()
213
214     sys.displayhook = displayhook
215
216     def excepthook(etype, evalue, etraceback):
217         lines = format_exception(etype, evalue, etraceback)
218         pager = Pager()
219         pager.stdout = ColoredFile(pager.stdout, '\033[31m')  # red
220         for line in lines:
221             pager.write(line)
222         pager.close()
223
224     sys.excepthook = excepthook
225
226     # try:
227     #     import cgitb
228     # except ImportError:
229     #     pass
230     # else:
231     #     # cgitb.enable() overrides sys.excepthook
232     #     cgitb.enable(format='text')
233
234     # From Thomas Heller:
235     # https://mail.python.org/pipermail/python-list/2001-April/099020.html
236
237     # import pdb
238     #
239     # def info(*args):
240     #    pdb.pm()
241     # sys.excepthook = info
242
243     # utilities
244
245     # From: Paul Magwene:
246     # https://mail.python.org/pipermail/python-list/2001-March/086191.html
247     # With a lot of my fixes:
248
249     class DirLister:
250         def __getitem__(self, key):
251             s = os.listdir(os.curdir)
252             return s[key]
253
254         def __getslice__(self, i, j):
255             s = os.listdir(os.curdir)
256             return s[i:j]
257
258         def __repr__(self):
259             return str(os.listdir(os.curdir))
260
261         def __call__(self, path=None):
262             if path:
263                 path = os.path.expanduser(os.path.expandvars(path))
264             else:
265                 path = os.curdir
266             return os.listdir(path)
267
268     class DirChanger:
269         def __repr__(self):
270             self()
271             return os.getcwd()
272
273         def __call__(self, path=None):
274             path = os.path.expanduser(os.path.expandvars(path or '~'))
275             os.chdir(path)
276
277     builtins.ls = DirLister()
278     builtins.cd = DirChanger()
279
280     # print working directory
281
282     class Pwd:
283         def __repr__(self):
284             return os.getcwd()
285
286         def __call__(self):
287             return repr(self)
288
289     builtins.pwd = Pwd()
290
291     # exit REPL with 'exit', 'quit' or simple 'x'
292
293     class _Exit:
294         def __repr__(self):
295             sys.exit()
296
297         def __call__(self, msg=None):
298             sys.exit(msg)
299
300     builtins.x = _Exit()
301
302     # print conten of a file
303
304     class _Cat:
305         def __repr__(self):
306             return "Usage: cat('filename')"
307
308         def __call__(self, filename):
309             fp = open(filename, 'rU')
310             text = fp.read()
311             fp.close()
312             print(text)
313
314     builtins.cat = _Cat()
315
316     # call shell
317
318     class _Sh:
319         def __repr__(self):
320             os.system(os.environ["SHELL"])
321             return ''
322
323         def __call__(self, cmdline):
324             os.system(cmdline)
325
326     builtins.sh = _Sh()
327
328     # paginate a file
329
330     class _Pager:
331         def __repr__(self):
332             return "Usage: pager('filename')"
333
334         def __call__(self, filename):
335             os.system("%s '%s'" % (pager, filename.replace("'", '"\'"')))
336
337     builtins.pager = _Pager()
338
339     # edit a file
340
341     class _Editor:
342         def __repr__(self):
343             return "Usage: edit('filename')"
344
345         def __call__(self, filename):
346             editor = os.environ.get("VISUAL") \
347                 or os.environ.get("EDITOR") or 'vi'
348             os.system("%s '%s'" % (editor, filename.replace("'", '"\'"')))
349
350     builtins.edit = builtins.editor = _Editor()
351
352
353 init()
354 del init