]> git.phdru.name Git - dotfiles.git/blob - lib/python/init.py
init.py: minor refactoring: move displayhook
[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 readline
31             initfile = os.environ.get('INPUTRC') \
32                 or os.path.expanduser('~/.inputrc')
33             readline.read_init_file(initfile)
34
35             histfile = os.path.expanduser('~/.python-history')
36             try:
37                 readline.read_history_file(histfile)
38             except IOError:
39                 pass  # No such file
40
41             def savehist():
42                 histfilesize = os.environ.get('HISTFILESIZE') \
43                     or os.environ.get('HISTSIZE')
44                 if histfilesize:
45                     try:
46                         histfilesize = int(histfilesize)
47                     except ValueError:
48                         pass
49                     else:
50                         readline.set_history_length(histfilesize)
51                 readline.write_history_file(histfile)
52
53             import atexit
54             atexit.register(savehist)
55
56         except (ImportError, AttributeError):
57             # no readline or atexit, or readline doesn't have
58             # {read,write}_history_file - ignore the error
59             pass
60
61     # terminal
62
63     term = os.environ.get('TERM', '')
64     if 'linux' in term:
65         background = 'dark'
66     else:
67         background = os.environ.get('BACKGROUND', 'light').lower()
68
69     # From Randall Hopper:
70     # https://mail.python.org/pipermail/python-list/2001-March/112696.html
71
72     for _term in ['linux', 'rxvt', 'screen', 'term', 'vt100']:
73         if _term not in term:
74             continue
75
76         if background == 'dark':
77             ps1_color = '3'  # yellow
78             stdout_color = '7'  # bold white
79         else:
80             ps1_color = '4'  # blue
81             stdout_color = '0'  # bold black
82
83         sys.ps1 = '\001\033[3%sm\002>>>\001\033[0m\002 ' % ps1_color
84         sys.ps2 = '\001\033[1;32m\002...\001\033[0m\002 '  # bold green
85
86         # From Denis Otkidach
87
88         class ColoredFile:
89             def __init__(self, fp, begin,
90                          end='\033[0m'):  # reset all attributes
91                 self.__fp = fp
92                 self.__begin = begin
93                 self.__end = end
94
95             def write(self, s):
96                 self.__fp.write(self.__begin+s+self.__end)
97
98             def writelines(self, lines):
99                 map(self.write, lines)
100
101             def __getattr__(self, attr):
102                 return getattr(self.__fp, attr)
103
104         sys.stdout = ColoredFile(sys.stdout, '\033[1;3%sm' % stdout_color)
105         sys.stderr = ColoredFile(sys.stderr, '\033[31m')  # red
106
107         break
108
109     try:
110         import locale
111     except ImportError:
112         pass  # locale was not compiled
113     else:
114         try:
115             locale.setlocale(locale.LC_ALL, '')
116
117         except (ImportError, locale.Error):
118             pass  # no locale support or unsupported locale
119
120     # set displayhook
121
122     from pprint import pprint
123
124     def displayhook(value):
125         if value is not None:
126             __builtin__._ = value
127             pprint(value)
128
129     sys.displayhook = displayhook
130
131     # utilities
132
133     # From: Paul Magwene:
134     # https://mail.python.org/pipermail/python-list/2001-March/086191.html
135     # With a lot of my fixes:
136
137     class DirLister:
138         def __getitem__(self, key):
139             s = os.listdir(os.curdir)
140             return s[key]
141
142         def __getslice__(self, i, j):
143             s = os.listdir(os.curdir)
144             return s[i:j]
145
146         def __repr__(self):
147             return str(os.listdir(os.curdir))
148
149         def __call__(self, path=None):
150             if path:
151                 path = os.path.expanduser(os.path.expandvars(path))
152             else:
153                 path = os.curdir
154             return os.listdir(path)
155
156     class DirChanger:
157         def __repr__(self):
158             self()
159             return os.getcwd()
160
161         def __call__(self, path=None):
162             path = os.path.expanduser(os.path.expandvars(path or '~'))
163             os.chdir(path)
164
165     __builtin__.ls = DirLister()
166     __builtin__.cd = DirChanger()
167
168     # From Thomas Heller:
169     # https://mail.python.org/pipermail/python-list/2001-April/099020.html
170
171     # import pdb
172     #
173     # def info(*args):
174     #    pdb.pm()
175     # sys.excepthook = info
176
177     # print working directory
178
179     class Pwd:
180         def __repr__(self):
181             return os.getcwd()
182
183         def __call__(self):
184             return repr(self)
185
186     __builtin__.pwd = Pwd()
187
188     # exit REPL with 'exit', 'quit' or simple 'x'
189
190     class _Exit:
191         def __repr__(self):
192             sys.exit()
193
194         def __call__(self, msg=None):
195             sys.exit(msg)
196
197     __builtin__.x = _Exit()
198
199     # In Python 2.5+ exit and quit are objects
200     if isinstance(__builtin__.exit, str):
201         __builtin__.exit = __builtin__.quit = x  # noqa: x is defined as _Exit
202
203     # print conten of a file
204
205     class _Cat:
206         def __repr__(self):
207             return "Usage: cat('filename')"
208
209         def __call__(self, filename):
210             fp = open(filename, 'rU')
211             text = fp.read()
212             fp.close()
213             print text
214
215     __builtin__.cat = _Cat()
216
217     # call shell
218
219     class _Sh:
220         def __repr__(self):
221             os.system(os.environ["SHELL"])
222             return ''
223
224         def __call__(self, cmdline):
225             os.system(cmdline)
226
227     __builtin__.sh = _Sh()
228
229     # paginate a file
230
231     class _Pager:
232         def __repr__(self):
233             return "Usage: pager('filename')"
234
235         def __call__(self, filename):
236             pager = os.environ.get("PAGER") or 'more'
237             os.system("%s '%s'" % (pager, filename.replace("'", '"\'"')))
238
239     __builtin__.pager = _Pager()
240
241     # edit a file
242
243     class _Editor:
244         def __repr__(self):
245             return "Usage: edit('filename')"
246
247         def __call__(self, filename):
248             editor = os.environ.get("VISUAL") \
249                 or os.environ.get("EDITOR") or 'vi'
250             os.system("%s '%s'" % (editor, filename.replace("'", '"\'"')))
251
252     __builtin__.edit = __builtin__.editor = _Editor()
253
254
255 init()
256 del init