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