forked from mathiasbynens/dotfiles
-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy path.pythonrc
378 lines (316 loc) · 11.6 KB
/
.pythonrc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
# -*- coding: utf-8 -*-
"""Startup script that adds niceties to the interactive interpreter.
This script adds the following things:
- Readline bindings, tab completion, and history (in ~/.history/python,
which can be disabled by setting NOHIST in the environment)
- Pretty printing of expression output (with Pygments highlighting)
- Pygments highlighting of tracebacks
- Function arguments in repr() for callables
- A source() function that displays the source of an arbitrary object
(in a pager, with Pygments highlighting)
Python 2.3 and newer are supported, including Python 3.x.
Note: The default versions of Python that ship with Mac OS X don't
come with readline. To get readline support, you can try a stand-alone
readline library[1], or you can use a different Python distribution
(like the one from MacPorts).
[1]: http://pypi.python.org/pypi/readline
"""
def _pythonrc_enable_readline():
"""Enable readline, tab completion, and history"""
import sys
try:
import readline
import rlcompleter
except ImportError:
sys.stderr.write('readline unavailable - tab completion disabled.\n')
return
old_complete = readline.get_completer()
def complete(text, state):
if not text:
# Insert four spaces for indentation
return (' ', None)[state]
else:
return old_complete(text, state)
readline.parse_and_bind('tab: complete')
readline.set_completer(complete)
def _pythonrc_enable_history():
import atexit
import os
try:
import readline
except:
return
# "NOHIST= python" will disable history
if 'NOHIST' not in os.environ:
history_path = os.path.expanduser('~/.history/python')
has_written = [False]
def write_history():
if not has_written[0]:
readline.write_history_file(history_path)
print('Written history to %s' % history_path)
has_written[0] = True
atexit.register(write_history)
if os.path.isfile(history_path):
try:
readline.read_history_file(history_path)
except IOError:
pass
readline.set_history_length(-1)
def _pythonrc_enable_pprint():
"""Enable pretty printing of evaluated expressions"""
import pprint
import sys
try:
if sys.platform == 'win32':
raise ImportError()
from cStringIO import StringIO
from pygments import highlight
from pygments.lexers import PythonLexer, PythonTracebackLexer
from pygments.formatters import TerminalFormatter
def pphighlight(o, *a, **kw):
s = pprint.pformat(o, *a, **kw)
try:
sys.stdout.write(
highlight(s, PythonLexer(), TerminalFormatter()))
except UnicodeError:
sys.stdout.write(s)
sys.stdout.write('\n')
_old_excepthook = sys.excepthook
def excepthook(exctype, value, traceback):
"""Prints exceptions to sys.stderr and colorizes them"""
# traceback.format_exception() isn't used because it's
# inconsistent with the built-in formatter
old_stderr = sys.stderr
sys.stderr = StringIO()
try:
_old_excepthook(exctype, value, traceback)
s = sys.stderr.getvalue()
try:
s = highlight(
s, PythonTracebackLexer(), TerminalFormatter())
except UnicodeError:
pass
old_stderr.write(s)
finally:
sys.stderr = old_stderr
sys.excepthook = excepthook
except ImportError:
pphighlight = pprint.pprint
try:
import __builtin__
except ImportError:
import builtins as __builtin__
import inspect
import pydoc
import sys
import types
help_types = [types.BuiltinFunctionType, types.BuiltinMethodType,
types.FunctionType, types.MethodType, types.ModuleType,
type,
# method_descriptor
type(list.remove)]
if hasattr(types, 'UnboundMethodType'):
help_types.append(types.UnboundMethodType)
help_types = tuple(help_types)
def _ioctl_width(fd):
from fcntl import ioctl
from struct import pack, unpack
from termios import TIOCGWINSZ
return unpack('HHHH',
ioctl(fd, TIOCGWINSZ, pack('HHHH', 0, 0, 0, 0)))[1]
def get_width():
"""Returns terminal width"""
width = 0
try:
width = _ioctl_width(0) or _ioctl_width(1) or _ioctl_width(2)
except ImportError:
pass
if not width:
import os
width = os.environ.get('COLUMNS', 0)
return width
if hasattr(inspect, 'getfullargspec'):
getargspec = inspect.getfullargspec
else:
getargspec = inspect.getargspec
def pprinthook(value):
"""Pretty print an object to sys.stdout and also save it in
__builtin__.
"""
if value is None:
return
__builtin__._ = value
if isinstance(value, help_types):
reprstr = repr(value)
try:
if inspect.isfunction(value):
parts = reprstr.split(' ')
parts[1] += inspect.formatargspec(*getargspec(value))
reprstr = ' '.join(parts)
elif inspect.ismethod(value):
parts = reprstr[:-1].split(' ')
parts[2] += inspect.formatargspec(*getargspec(value))
reprstr = ' '.join(parts) + '>'
except TypeError:
pass
sys.stdout.write(reprstr)
sys.stdout.write('\n')
if getattr(value, '__doc__', None):
sys.stdout.write('\n')
sys.stdout.write(pydoc.getdoc(value))
sys.stdout.write('\n')
else:
pphighlight(value, width=get_width() or 80)
sys.displayhook = pprinthook
def _pythonrc_fix_linecache():
"""Add source(obj) that shows the source code for a given object"""
import os
import sys
from linecache import cache
# linecache.updatecache() replacement that actually works with zips.
# See http://bugs.python.org/issue4223 for more information.
def updatecache(filename, module_globals=None):
"""Update a cache entry and return its list of lines.
If something's wrong, print a message, discard the cache entry,
and return an empty list."""
if filename in cache:
del cache[filename]
if not filename or filename[0] + filename[-1] == '<>':
return []
fullname = filename
try:
stat = os.stat(fullname)
except os.error:
basename = os.path.split(filename)[1]
if module_globals and '__loader__' in module_globals:
name = module_globals.get('__name__')
loader = module_globals['__loader__']
get_source = getattr(loader, 'get_source', None)
if name and get_source:
try:
data = get_source(name)
except (ImportError, IOError):
pass
else:
if data is None:
return []
cache[filename] = (
len(data), None,
[line + '\n' for line in data.splitlines()],
fullname
)
return cache[filename][2]
for dirname in sys.path:
try:
fullname = os.path.join(dirname, basename)
except (TypeError, AttributeError):
pass
else:
try:
stat = os.stat(fullname)
break
except os.error:
pass
else:
return []
try:
fp = open(fullname, 'rU')
lines = fp.readlines()
fp.close()
except IOError:
return []
size, mtime = stat.st_size, stat.st_mtime
cache[filename] = size, mtime, lines, fullname
return lines
import linecache
linecache.updatecache = updatecache
def source(obj):
"""Display the source code of an object.
Applies syntax highlighting if Pygments is available.
"""
import os
import sys
from inspect import findsource, getmodule, getsource, getsourcefile
from pydoc import pager
try:
# Check to see if the object is defined in a shared library, which
# findsource() doesn't do properly (see issue4050)
if not getsourcefile(obj):
raise TypeError
s = getsource(obj)
except TypeError:
sys.stderr.write("Source code unavailable (maybe it's part of "
"a C extension?)\n")
return
# Detect the module's file encoding. We could use
# tokenize.detect_encoding(), but it's only available in Python 3.
import re
enc = 'ascii'
for line in findsource(getmodule(obj))[0][:2]:
m = re.search(r'coding[:=]\s*([-\w.]+)', line)
if m:
enc = m.group(1)
if hasattr(s, 'decode'):
try:
s = s.decode(enc, 'replace')
except LookupError:
s = s.decode('ascii', 'replace')
try:
# For now, let's assume we'll never have a proper terminal on win32
if sys.platform == 'win32':
raise ImportError
from pygments import highlight
from pygments.lexers import PythonLexer
from pygments.formatters import TerminalFormatter
s = highlight(s, PythonLexer(), TerminalFormatter())
except (ImportError, UnicodeError):
pass
# Display the source code in the pager, and try to convince less not to
# escape color control codes.
has_lessopts = 'LESS' in os.environ
lessopts = os.environ.get('LESS', '')
try:
os.environ['LESS'] = lessopts + ' -R'
if hasattr(s, 'decode'):
pager(s.encode(sys.stdout.encoding, 'replace'))
else:
pager(s)
finally:
if has_lessopts:
os.environ['LESS'] = lessopts
else:
os.environ.pop('LESS', None)
if __name__ == '__main__':
__doc__ = None
# Make sure modules in the current directory can't interfere
import sys
try:
try:
cwd = sys.path.index('')
sys.path.pop(cwd)
except ValueError:
cwd = None
sys.ps1 = "\001\033[0;32m\002>>> \001\033[1;37m\002"
sys.ps2 = "\001\033[1;31m\002... \001\033[1;37m\002"
# Run installation functions and don't taint the global namespace
try:
try:
import jedi.utils
jedi.utils.setup_readline()
del jedi
except:
print('No jedi here. Coming to the dark side.')
_pythonrc_enable_readline()
del _pythonrc_enable_readline
_pythonrc_enable_history()
_pythonrc_enable_pprint()
_pythonrc_fix_linecache()
del _pythonrc_enable_history
del _pythonrc_enable_pprint
del _pythonrc_fix_linecache
finally:
if cwd is not None:
sys.path.insert(cwd, '')
del cwd
finally:
pass