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