]> git.phdru.name Git - dotfiles.git/blob - lib/python/init.py
Fix(init.py): Do not intercept EOF in `myinput`
[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             result = builtin_input(prompt)
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         if _term_found:
179             def pprint(self, value):
180                 pprint(value,
181                        stream=ColoredFile(self.stdout,
182                                           '\033[1;3%sm' % stdout_color))
183
184         def close(self):
185             self.stdout.close()
186
187     try:
188         from subprocess import Popen, PIPE
189     except ImportError:
190         class Pager(BasePager):
191             def __init__(self):
192                 self.stdout = os.popen(pager, 'w')
193     else:
194         class Pager(BasePager):
195             def __init__(self):
196                 self.pipe = Popen(pager, shell=True, stdin=PIPE,
197                                   universal_newlines=True)
198                 self.stdout = self.pipe.stdin
199
200             def close(self):
201                 BasePager.close(self)
202                 self.pipe.wait()
203
204     def displayhook(value):
205         if value is not None:
206             builtins._ = value
207         pager = Pager()
208         try:
209             pager.pprint(value)
210         except:  # noqa
211             if _term_found:
212                 pager.stdout = ColoredFile(pager.stdout, '\033[31m')  # red
213             print_exc(file=pager)
214         pager.close()
215
216     sys.displayhook = displayhook
217
218     def excepthook(etype, evalue, etraceback):
219         lines = format_exception(etype, evalue, etraceback)
220         pager = Pager()
221         if _term_found:
222             pager.stdout = ColoredFile(pager.stdout, '\033[31m')  # red
223         for line in lines:
224             pager.write(line)
225         pager.close()
226
227     sys.excepthook = excepthook
228
229     # try:
230     #     import cgitb
231     # except ImportError:
232     #     pass
233     # else:
234     #     # cgitb.enable() overrides sys.excepthook
235     #     cgitb.enable(format='text')
236
237     # From Thomas Heller:
238     # https://mail.python.org/pipermail/python-list/2001-April/099020.html
239
240     # import pdb
241     #
242     # def info(*args):
243     #    pdb.pm()
244     # sys.excepthook = info
245
246     # utilities
247
248     # From: Paul Magwene:
249     # https://mail.python.org/pipermail/python-list/2001-March/086191.html
250     # With a lot of my fixes:
251
252     class DirLister:
253         def __getitem__(self, key):
254             s = os.listdir(os.curdir)
255             return s[key]
256
257         def __getslice__(self, i, j):
258             s = os.listdir(os.curdir)
259             return s[i:j]
260
261         def __repr__(self):
262             return str(os.listdir(os.curdir))
263
264         def __call__(self, path=None):
265             if path:
266                 path = os.path.expanduser(os.path.expandvars(path))
267             else:
268                 path = os.curdir
269             return os.listdir(path)
270
271     class DirChanger:
272         def __repr__(self):
273             self()
274             return os.getcwd()
275
276         def __call__(self, path=None):
277             path = os.path.expanduser(os.path.expandvars(path or '~'))
278             os.chdir(path)
279
280     builtins.ls = DirLister()
281     builtins.cd = DirChanger()
282
283     # print working directory
284
285     class Pwd:
286         def __repr__(self):
287             return os.getcwd()
288
289         def __call__(self):
290             return repr(self)
291
292     builtins.pwd = Pwd()
293
294     # exit REPL with 'exit', 'quit' or simple 'x'
295
296     class _Exit:
297         def __repr__(self):
298             sys.exit()
299
300         def __call__(self, msg=None):
301             sys.exit(msg)
302
303     builtins.x = _Exit()
304
305     # print conten of a file
306
307     class _Cat:
308         def __repr__(self):
309             return "Usage: cat('filename')"
310
311         def __call__(self, filename):
312             fp = open(filename, 'rU')
313             text = fp.read()
314             fp.close()
315             print(text)
316
317     builtins.cat = _Cat()
318
319     # call shell
320
321     class _Sh:
322         def __repr__(self):
323             os.system(os.environ["SHELL"])
324             return ''
325
326         def __call__(self, cmdline):
327             os.system(cmdline)
328
329     builtins.sh = _Sh()
330
331     # paginate a file
332
333     class _Pager:
334         def __repr__(self):
335             return "Usage: pager('filename')"
336
337         def __call__(self, filename):
338             os.system("%s '%s'" % (pager, filename.replace("'", '"\'"')))
339
340     builtins.pager = _Pager()
341
342     # edit a file
343
344     class _Editor:
345         def __repr__(self):
346             return "Usage: edit('filename')"
347
348         def __call__(self, filename):
349             editor = os.environ.get("VISUAL") \
350                 or os.environ.get("EDITOR") or 'vi'
351             os.system("%s '%s'" % (editor, filename.replace("'", '"\'"')))
352
353     builtins.edit = builtins.editor = _Editor()
354
355
356 init()
357 del init