]> git.phdru.name Git - dotfiles.git/blob - lib/python/init.py
lib/python/init.py: rename pager.stdin to stdout
[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     pager = os.environ.get("PAGER") or 'more'
126
127     # if your pager is 'less', options '-F' and '-R' must be passed to it,
128     # and option '-X' is very much recommended
129     if pager == 'less':
130         less = os.environ.get("LESS") or ''
131         for opt in 'X', 'R', 'F':
132             if opt not in less:
133                 less = opt + less
134         os.environ["LESS"] = less
135
136     class BasePager:
137         def write(self, value):
138             self.stdout.write(value)
139
140         def pprint(self, value):
141             pprint(value,
142                    stream=ColoredFile(self.stdout,
143                                       '\033[1;3%sm' % stdout_color))
144
145         def close(self):
146             self.stdout.close()
147
148     try:
149         from subprocess import Popen, PIPE
150     except ImportError:
151         class Pager(BasePager):
152             def __init__(self):
153                 self.pipe = Popen(pager, shell=True, stdin=PIPE)
154                 self.stdout = self.pipe.stdin
155
156             def close(self):
157                 BasePager.close(self)
158                 self.pipe.wait()
159     else:
160         class Pager(BasePager):
161             def __init__(self):
162                 self.stdout = os.popen(pager, 'w')
163
164     def displayhook(value):
165         if value is not None:
166             builtins._ = value
167         pager = Pager()
168         pager.pprint(value)
169         pager.close()
170
171     sys.displayhook = displayhook
172
173     from traceback import format_exception
174
175     def excepthook(etype, evalue, etraceback):
176         lines = format_exception(etype, evalue, etraceback)
177         pager = Pager()
178         for line in lines:
179             pager.write(
180                 '\033[31m' + line.rstrip('\n') + '\033[0m\n')  # red, reset
181         pager.close()
182
183     sys.excepthook = excepthook
184
185     #try:
186     #    import cgitb
187     #except ImportError:
188     #    pass
189     #else:
190     #    # cgitb.enable() overrides sys.excepthook
191     #    cgitb.enable(format='text')
192
193     # From Thomas Heller:
194     # https://mail.python.org/pipermail/python-list/2001-April/099020.html
195
196     # import pdb
197     #
198     # def info(*args):
199     #    pdb.pm()
200     # sys.excepthook = info
201
202     # utilities
203
204     # From: Paul Magwene:
205     # https://mail.python.org/pipermail/python-list/2001-March/086191.html
206     # With a lot of my fixes:
207
208     class DirLister:
209         def __getitem__(self, key):
210             s = os.listdir(os.curdir)
211             return s[key]
212
213         def __getslice__(self, i, j):
214             s = os.listdir(os.curdir)
215             return s[i:j]
216
217         def __repr__(self):
218             return str(os.listdir(os.curdir))
219
220         def __call__(self, path=None):
221             if path:
222                 path = os.path.expanduser(os.path.expandvars(path))
223             else:
224                 path = os.curdir
225             return os.listdir(path)
226
227     class DirChanger:
228         def __repr__(self):
229             self()
230             return os.getcwd()
231
232         def __call__(self, path=None):
233             path = os.path.expanduser(os.path.expandvars(path or '~'))
234             os.chdir(path)
235
236     builtins.ls = DirLister()
237     builtins.cd = DirChanger()
238
239     # print working directory
240
241     class Pwd:
242         def __repr__(self):
243             return os.getcwd()
244
245         def __call__(self):
246             return repr(self)
247
248     builtins.pwd = Pwd()
249
250     # exit REPL with 'exit', 'quit' or simple 'x'
251
252     class _Exit:
253         def __repr__(self):
254             sys.exit()
255
256         def __call__(self, msg=None):
257             sys.exit(msg)
258
259     builtins.x = _Exit()
260
261     # In Python 2.5+ exit and quit are objects
262     if isinstance(builtins.exit, str):
263         builtins.exit = builtins.quit = x  # noqa: x is defined as _Exit
264
265     # print conten of a file
266
267     class _Cat:
268         def __repr__(self):
269             return "Usage: cat('filename')"
270
271         def __call__(self, filename):
272             fp = open(filename, 'rU')
273             text = fp.read()
274             fp.close()
275             print(text)
276
277     builtins.cat = _Cat()
278
279     # call shell
280
281     class _Sh:
282         def __repr__(self):
283             os.system(os.environ["SHELL"])
284             return ''
285
286         def __call__(self, cmdline):
287             os.system(cmdline)
288
289     builtins.sh = _Sh()
290
291     # paginate a file
292
293     class _Pager:
294         def __repr__(self):
295             return "Usage: pager('filename')"
296
297         def __call__(self, filename):
298             os.system("%s '%s'" % (pager, filename.replace("'", '"\'"')))
299
300     builtins.pager = _Pager()
301
302     # edit a file
303
304     class _Editor:
305         def __repr__(self):
306             return "Usage: edit('filename')"
307
308         def __call__(self, filename):
309             editor = os.environ.get("VISUAL") \
310                 or os.environ.get("EDITOR") or 'vi'
311             os.system("%s '%s'" % (editor, filename.replace("'", '"\'"')))
312
313     builtins.edit = builtins.editor = _Editor()
314
315
316 init()
317 del init