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