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