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