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