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