##// END OF EJS Templates
Changing how IPython.utils.io.Term is handled....
Brian Granger -
Show More

The requested changes are too big and content was truncated. Show full diff

@@ -1,510 +1,510 b''
1 1 # -*- coding: utf-8 -*-
2 2 """
3 3 Pdb debugger class.
4 4
5 5 Modified from the standard pdb.Pdb class to avoid including readline, so that
6 6 the command line completion of other programs which include this isn't
7 7 damaged.
8 8
9 9 In the future, this class will be expanded with improvements over the standard
10 10 pdb.
11 11
12 12 The code in this file is mainly lifted out of cmd.py in Python 2.2, with minor
13 13 changes. Licensing should therefore be under the standard Python terms. For
14 14 details on the PSF (Python Software Foundation) standard license, see:
15 15
16 16 http://www.python.org/2.2.3/license.html"""
17 17
18 18 #*****************************************************************************
19 19 #
20 20 # This file is licensed under the PSF license.
21 21 #
22 22 # Copyright (C) 2001 Python Software Foundation, www.python.org
23 23 # Copyright (C) 2005-2006 Fernando Perez. <fperez@colorado.edu>
24 24 #
25 25 #
26 26 #*****************************************************************************
27 27
28 28 import bdb
29 29 import linecache
30 30 import sys
31 31
32 32 from IPython.utils import PyColorize
33 33 from IPython.core import ipapi
34 34 from IPython.utils import coloransi
35 from IPython.utils.io import Term
35 import IPython.utils.io
36 36 from IPython.core.excolors import exception_colors
37 37
38 38 # See if we can use pydb.
39 39 has_pydb = False
40 40 prompt = 'ipdb> '
41 41 #We have to check this directly from sys.argv, config struct not yet available
42 42 if '-pydb' in sys.argv:
43 43 try:
44 44 import pydb
45 45 if hasattr(pydb.pydb, "runl") and pydb.version>'1.17':
46 46 # Version 1.17 is broken, and that's what ships with Ubuntu Edgy, so we
47 47 # better protect against it.
48 48 has_pydb = True
49 49 except ImportError:
50 50 print "Pydb (http://bashdb.sourceforge.net/pydb/) does not seem to be available"
51 51
52 52 if has_pydb:
53 53 from pydb import Pdb as OldPdb
54 54 #print "Using pydb for %run -d and post-mortem" #dbg
55 55 prompt = 'ipydb> '
56 56 else:
57 57 from pdb import Pdb as OldPdb
58 58
59 59 # Allow the set_trace code to operate outside of an ipython instance, even if
60 60 # it does so with some limitations. The rest of this support is implemented in
61 61 # the Tracer constructor.
62 62 def BdbQuit_excepthook(et,ev,tb):
63 63 if et==bdb.BdbQuit:
64 64 print 'Exiting Debugger.'
65 65 else:
66 66 BdbQuit_excepthook.excepthook_ori(et,ev,tb)
67 67
68 68 def BdbQuit_IPython_excepthook(self,et,ev,tb):
69 69 print 'Exiting Debugger.'
70 70
71 71
72 72 class Tracer(object):
73 73 """Class for local debugging, similar to pdb.set_trace.
74 74
75 75 Instances of this class, when called, behave like pdb.set_trace, but
76 76 providing IPython's enhanced capabilities.
77 77
78 78 This is implemented as a class which must be initialized in your own code
79 79 and not as a standalone function because we need to detect at runtime
80 80 whether IPython is already active or not. That detection is done in the
81 81 constructor, ensuring that this code plays nicely with a running IPython,
82 82 while functioning acceptably (though with limitations) if outside of it.
83 83 """
84 84
85 85 def __init__(self,colors=None):
86 86 """Create a local debugger instance.
87 87
88 88 :Parameters:
89 89
90 90 - `colors` (None): a string containing the name of the color scheme to
91 91 use, it must be one of IPython's valid color schemes. If not given, the
92 92 function will default to the current IPython scheme when running inside
93 93 IPython, and to 'NoColor' otherwise.
94 94
95 95 Usage example:
96 96
97 97 from IPython.core.debugger import Tracer; debug_here = Tracer()
98 98
99 99 ... later in your code
100 100 debug_here() # -> will open up the debugger at that point.
101 101
102 102 Once the debugger activates, you can use all of its regular commands to
103 103 step through code, set breakpoints, etc. See the pdb documentation
104 104 from the Python standard library for usage details.
105 105 """
106 106
107 107 try:
108 108 ip = ipapi.get()
109 109 except:
110 110 # Outside of ipython, we set our own exception hook manually
111 111 BdbQuit_excepthook.excepthook_ori = sys.excepthook
112 112 sys.excepthook = BdbQuit_excepthook
113 113 def_colors = 'NoColor'
114 114 try:
115 115 # Limited tab completion support
116 116 import readline
117 117 readline.parse_and_bind('tab: complete')
118 118 except ImportError:
119 119 pass
120 120 else:
121 121 # In ipython, we use its custom exception handler mechanism
122 122 def_colors = ip.colors
123 123 ip.set_custom_exc((bdb.BdbQuit,), BdbQuit_IPython_excepthook)
124 124
125 125 if colors is None:
126 126 colors = def_colors
127 127 self.debugger = Pdb(colors)
128 128
129 129 def __call__(self):
130 130 """Starts an interactive debugger at the point where called.
131 131
132 132 This is similar to the pdb.set_trace() function from the std lib, but
133 133 using IPython's enhanced debugger."""
134 134
135 135 self.debugger.set_trace(sys._getframe().f_back)
136 136
137 137
138 138 def decorate_fn_with_doc(new_fn, old_fn, additional_text=""):
139 139 """Make new_fn have old_fn's doc string. This is particularly useful
140 140 for the do_... commands that hook into the help system.
141 141 Adapted from from a comp.lang.python posting
142 142 by Duncan Booth."""
143 143 def wrapper(*args, **kw):
144 144 return new_fn(*args, **kw)
145 145 if old_fn.__doc__:
146 146 wrapper.__doc__ = old_fn.__doc__ + additional_text
147 147 return wrapper
148 148
149 149
150 150 def _file_lines(fname):
151 151 """Return the contents of a named file as a list of lines.
152 152
153 153 This function never raises an IOError exception: if the file can't be
154 154 read, it simply returns an empty list."""
155 155
156 156 try:
157 157 outfile = open(fname)
158 158 except IOError:
159 159 return []
160 160 else:
161 161 out = outfile.readlines()
162 162 outfile.close()
163 163 return out
164 164
165 165
166 166 class Pdb(OldPdb):
167 167 """Modified Pdb class, does not load readline."""
168 168
169 169 def __init__(self,color_scheme='NoColor',completekey=None,
170 170 stdin=None, stdout=None):
171 171
172 172 # Parent constructor:
173 173 if has_pydb and completekey is None:
174 OldPdb.__init__(self,stdin=stdin,stdout=Term.cout)
174 OldPdb.__init__(self,stdin=stdin,stdout=IPython.utils.io.Term.cout)
175 175 else:
176 176 OldPdb.__init__(self,completekey,stdin,stdout)
177 177
178 178 self.prompt = prompt # The default prompt is '(Pdb)'
179 179
180 180 # IPython changes...
181 181 self.is_pydb = has_pydb
182 182
183 183 self.shell = ipapi.get()
184 184
185 185 if self.is_pydb:
186 186
187 187 # interactiveshell.py's ipalias seems to want pdb's checkline
188 188 # which located in pydb.fn
189 189 import pydb.fns
190 190 self.checkline = lambda filename, lineno: \
191 191 pydb.fns.checkline(self, filename, lineno)
192 192
193 193 self.curframe = None
194 194 self.do_restart = self.new_do_restart
195 195
196 196 self.old_all_completions = self.shell.Completer.all_completions
197 197 self.shell.Completer.all_completions=self.all_completions
198 198
199 199 self.do_list = decorate_fn_with_doc(self.list_command_pydb,
200 200 OldPdb.do_list)
201 201 self.do_l = self.do_list
202 202 self.do_frame = decorate_fn_with_doc(self.new_do_frame,
203 203 OldPdb.do_frame)
204 204
205 205 self.aliases = {}
206 206
207 207 # Create color table: we copy the default one from the traceback
208 208 # module and add a few attributes needed for debugging
209 209 self.color_scheme_table = exception_colors()
210 210
211 211 # shorthands
212 212 C = coloransi.TermColors
213 213 cst = self.color_scheme_table
214 214
215 215 cst['NoColor'].colors.breakpoint_enabled = C.NoColor
216 216 cst['NoColor'].colors.breakpoint_disabled = C.NoColor
217 217
218 218 cst['Linux'].colors.breakpoint_enabled = C.LightRed
219 219 cst['Linux'].colors.breakpoint_disabled = C.Red
220 220
221 221 cst['LightBG'].colors.breakpoint_enabled = C.LightRed
222 222 cst['LightBG'].colors.breakpoint_disabled = C.Red
223 223
224 224 self.set_colors(color_scheme)
225 225
226 226 # Add a python parser so we can syntax highlight source while
227 227 # debugging.
228 228 self.parser = PyColorize.Parser()
229 229
230 230 def set_colors(self, scheme):
231 231 """Shorthand access to the color table scheme selector method."""
232 232 self.color_scheme_table.set_active_scheme(scheme)
233 233
234 234 def interaction(self, frame, traceback):
235 235 self.shell.set_completer_frame(frame)
236 236 OldPdb.interaction(self, frame, traceback)
237 237
238 238 def new_do_up(self, arg):
239 239 OldPdb.do_up(self, arg)
240 240 self.shell.set_completer_frame(self.curframe)
241 241 do_u = do_up = decorate_fn_with_doc(new_do_up, OldPdb.do_up)
242 242
243 243 def new_do_down(self, arg):
244 244 OldPdb.do_down(self, arg)
245 245 self.shell.set_completer_frame(self.curframe)
246 246
247 247 do_d = do_down = decorate_fn_with_doc(new_do_down, OldPdb.do_down)
248 248
249 249 def new_do_frame(self, arg):
250 250 OldPdb.do_frame(self, arg)
251 251 self.shell.set_completer_frame(self.curframe)
252 252
253 253 def new_do_quit(self, arg):
254 254
255 255 if hasattr(self, 'old_all_completions'):
256 256 self.shell.Completer.all_completions=self.old_all_completions
257 257
258 258
259 259 return OldPdb.do_quit(self, arg)
260 260
261 261 do_q = do_quit = decorate_fn_with_doc(new_do_quit, OldPdb.do_quit)
262 262
263 263 def new_do_restart(self, arg):
264 264 """Restart command. In the context of ipython this is exactly the same
265 265 thing as 'quit'."""
266 266 self.msg("Restart doesn't make sense here. Using 'quit' instead.")
267 267 return self.do_quit(arg)
268 268
269 269 def postloop(self):
270 270 self.shell.set_completer_frame(None)
271 271
272 272 def print_stack_trace(self):
273 273 try:
274 274 for frame_lineno in self.stack:
275 275 self.print_stack_entry(frame_lineno, context = 5)
276 276 except KeyboardInterrupt:
277 277 pass
278 278
279 279 def print_stack_entry(self,frame_lineno,prompt_prefix='\n-> ',
280 280 context = 3):
281 281 #frame, lineno = frame_lineno
282 print >>Term.cout, self.format_stack_entry(frame_lineno, '', context)
282 print >>IPython.utils.io.Term.cout, self.format_stack_entry(frame_lineno, '', context)
283 283
284 284 # vds: >>
285 285 frame, lineno = frame_lineno
286 286 filename = frame.f_code.co_filename
287 287 self.shell.hooks.synchronize_with_editor(filename, lineno, 0)
288 288 # vds: <<
289 289
290 290 def format_stack_entry(self, frame_lineno, lprefix=': ', context = 3):
291 291 import linecache, repr
292 292
293 293 ret = []
294 294
295 295 Colors = self.color_scheme_table.active_colors
296 296 ColorsNormal = Colors.Normal
297 297 tpl_link = '%s%%s%s' % (Colors.filenameEm, ColorsNormal)
298 298 tpl_call = '%s%%s%s%%s%s' % (Colors.vName, Colors.valEm, ColorsNormal)
299 299 tpl_line = '%%s%s%%s %s%%s' % (Colors.lineno, ColorsNormal)
300 300 tpl_line_em = '%%s%s%%s %s%%s%s' % (Colors.linenoEm, Colors.line,
301 301 ColorsNormal)
302 302
303 303 frame, lineno = frame_lineno
304 304
305 305 return_value = ''
306 306 if '__return__' in frame.f_locals:
307 307 rv = frame.f_locals['__return__']
308 308 #return_value += '->'
309 309 return_value += repr.repr(rv) + '\n'
310 310 ret.append(return_value)
311 311
312 312 #s = filename + '(' + `lineno` + ')'
313 313 filename = self.canonic(frame.f_code.co_filename)
314 314 link = tpl_link % filename
315 315
316 316 if frame.f_code.co_name:
317 317 func = frame.f_code.co_name
318 318 else:
319 319 func = "<lambda>"
320 320
321 321 call = ''
322 322 if func != '?':
323 323 if '__args__' in frame.f_locals:
324 324 args = repr.repr(frame.f_locals['__args__'])
325 325 else:
326 326 args = '()'
327 327 call = tpl_call % (func, args)
328 328
329 329 # The level info should be generated in the same format pdb uses, to
330 330 # avoid breaking the pdbtrack functionality of python-mode in *emacs.
331 331 if frame is self.curframe:
332 332 ret.append('> ')
333 333 else:
334 334 ret.append(' ')
335 335 ret.append('%s(%s)%s\n' % (link,lineno,call))
336 336
337 337 start = lineno - 1 - context//2
338 338 lines = linecache.getlines(filename)
339 339 start = max(start, 0)
340 340 start = min(start, len(lines) - context)
341 341 lines = lines[start : start + context]
342 342
343 343 for i,line in enumerate(lines):
344 344 show_arrow = (start + 1 + i == lineno)
345 345 linetpl = (frame is self.curframe or show_arrow) \
346 346 and tpl_line_em \
347 347 or tpl_line
348 348 ret.append(self.__format_line(linetpl, filename,
349 349 start + 1 + i, line,
350 350 arrow = show_arrow) )
351 351
352 352 return ''.join(ret)
353 353
354 354 def __format_line(self, tpl_line, filename, lineno, line, arrow = False):
355 355 bp_mark = ""
356 356 bp_mark_color = ""
357 357
358 358 scheme = self.color_scheme_table.active_scheme_name
359 359 new_line, err = self.parser.format2(line, 'str', scheme)
360 360 if not err: line = new_line
361 361
362 362 bp = None
363 363 if lineno in self.get_file_breaks(filename):
364 364 bps = self.get_breaks(filename, lineno)
365 365 bp = bps[-1]
366 366
367 367 if bp:
368 368 Colors = self.color_scheme_table.active_colors
369 369 bp_mark = str(bp.number)
370 370 bp_mark_color = Colors.breakpoint_enabled
371 371 if not bp.enabled:
372 372 bp_mark_color = Colors.breakpoint_disabled
373 373
374 374 numbers_width = 7
375 375 if arrow:
376 376 # This is the line with the error
377 377 pad = numbers_width - len(str(lineno)) - len(bp_mark)
378 378 if pad >= 3:
379 379 marker = '-'*(pad-3) + '-> '
380 380 elif pad == 2:
381 381 marker = '> '
382 382 elif pad == 1:
383 383 marker = '>'
384 384 else:
385 385 marker = ''
386 386 num = '%s%s' % (marker, str(lineno))
387 387 line = tpl_line % (bp_mark_color + bp_mark, num, line)
388 388 else:
389 389 num = '%*s' % (numbers_width - len(bp_mark), str(lineno))
390 390 line = tpl_line % (bp_mark_color + bp_mark, num, line)
391 391
392 392 return line
393 393
394 394 def list_command_pydb(self, arg):
395 395 """List command to use if we have a newer pydb installed"""
396 396 filename, first, last = OldPdb.parse_list_cmd(self, arg)
397 397 if filename is not None:
398 398 self.print_list_lines(filename, first, last)
399 399
400 400 def print_list_lines(self, filename, first, last):
401 401 """The printing (as opposed to the parsing part of a 'list'
402 402 command."""
403 403 try:
404 404 Colors = self.color_scheme_table.active_colors
405 405 ColorsNormal = Colors.Normal
406 406 tpl_line = '%%s%s%%s %s%%s' % (Colors.lineno, ColorsNormal)
407 407 tpl_line_em = '%%s%s%%s %s%%s%s' % (Colors.linenoEm, Colors.line, ColorsNormal)
408 408 src = []
409 409 for lineno in range(first, last+1):
410 410 line = linecache.getline(filename, lineno)
411 411 if not line:
412 412 break
413 413
414 414 if lineno == self.curframe.f_lineno:
415 415 line = self.__format_line(tpl_line_em, filename, lineno, line, arrow = True)
416 416 else:
417 417 line = self.__format_line(tpl_line, filename, lineno, line, arrow = False)
418 418
419 419 src.append(line)
420 420 self.lineno = lineno
421 421
422 print >>Term.cout, ''.join(src)
422 print >>IPython.utils.io.Term.cout, ''.join(src)
423 423
424 424 except KeyboardInterrupt:
425 425 pass
426 426
427 427 def do_list(self, arg):
428 428 self.lastcmd = 'list'
429 429 last = None
430 430 if arg:
431 431 try:
432 432 x = eval(arg, {}, {})
433 433 if type(x) == type(()):
434 434 first, last = x
435 435 first = int(first)
436 436 last = int(last)
437 437 if last < first:
438 438 # Assume it's a count
439 439 last = first + last
440 440 else:
441 441 first = max(1, int(x) - 5)
442 442 except:
443 443 print '*** Error in argument:', `arg`
444 444 return
445 445 elif self.lineno is None:
446 446 first = max(1, self.curframe.f_lineno - 5)
447 447 else:
448 448 first = self.lineno + 1
449 449 if last is None:
450 450 last = first + 10
451 451 self.print_list_lines(self.curframe.f_code.co_filename, first, last)
452 452
453 453 # vds: >>
454 454 lineno = first
455 455 filename = self.curframe.f_code.co_filename
456 456 self.shell.hooks.synchronize_with_editor(filename, lineno, 0)
457 457 # vds: <<
458 458
459 459 do_l = do_list
460 460
461 461 def do_pdef(self, arg):
462 462 """The debugger interface to magic_pdef"""
463 463 namespaces = [('Locals', self.curframe.f_locals),
464 464 ('Globals', self.curframe.f_globals)]
465 465 self.shell.magic_pdef(arg, namespaces=namespaces)
466 466
467 467 def do_pdoc(self, arg):
468 468 """The debugger interface to magic_pdoc"""
469 469 namespaces = [('Locals', self.curframe.f_locals),
470 470 ('Globals', self.curframe.f_globals)]
471 471 self.shell.magic_pdoc(arg, namespaces=namespaces)
472 472
473 473 def do_pinfo(self, arg):
474 474 """The debugger equivalant of ?obj"""
475 475 namespaces = [('Locals', self.curframe.f_locals),
476 476 ('Globals', self.curframe.f_globals)]
477 477 self.shell.magic_pinfo("pinfo %s" % arg, namespaces=namespaces)
478 478
479 479 def checkline(self, filename, lineno):
480 480 """Check whether specified line seems to be executable.
481 481
482 482 Return `lineno` if it is, 0 if not (e.g. a docstring, comment, blank
483 483 line or EOF). Warning: testing is not comprehensive.
484 484 """
485 485 #######################################################################
486 486 # XXX Hack! Use python-2.5 compatible code for this call, because with
487 487 # all of our changes, we've drifted from the pdb api in 2.6. For now,
488 488 # changing:
489 489 #
490 490 #line = linecache.getline(filename, lineno, self.curframe.f_globals)
491 491 # to:
492 492 #
493 493 line = linecache.getline(filename, lineno)
494 494 #
495 495 # does the trick. But in reality, we need to fix this by reconciling
496 496 # our updates with the new Pdb APIs in Python 2.6.
497 497 #
498 498 # End hack. The rest of this method is copied verbatim from 2.6 pdb.py
499 499 #######################################################################
500 500
501 501 if not line:
502 502 print >>self.stdout, 'End of file'
503 503 return 0
504 504 line = line.strip()
505 505 # Don't allow setting breakpoint at a blank line
506 506 if (not line or (line[0] == '#') or
507 507 (line[:3] == '"""') or line[:3] == "'''"):
508 508 print >>self.stdout, '*** Blank or comment'
509 509 return 0
510 510 return lineno
@@ -1,277 +1,278 b''
1 1 # -*- coding: utf-8 -*-
2 2 """ History related magics and functionality """
3 3
4 4 # Stdlib imports
5 5 import fnmatch
6 6 import os
7 7
8 from IPython.utils.io import Term, ask_yes_no
8 import IPython.utils.io
9 from IPython.utils.io import ask_yes_no
9 10 from IPython.utils.warn import warn
10 11 from IPython.core import ipapi
11 12
12 13 def magic_history(self, parameter_s = ''):
13 14 """Print input history (_i<n> variables), with most recent last.
14 15
15 16 %history -> print at most 40 inputs (some may be multi-line)\\
16 17 %history n -> print at most n inputs\\
17 18 %history n1 n2 -> print inputs between n1 and n2 (n2 not included)\\
18 19
19 20 By default, input history is printed without line numbers so it can be
20 21 directly pasted into an editor.
21 22
22 23 With -n, each input's number <n> is shown, and is accessible as the
23 24 automatically generated variable _i<n> as well as In[<n>]. Multi-line
24 25 statements are printed starting at a new line for easy copy/paste.
25 26
26 27 Options:
27 28
28 29 -n: print line numbers for each input.
29 30 This feature is only available if numbered prompts are in use.
30 31
31 32 -o: also print outputs for each input.
32 33
33 34 -p: print classic '>>>' python prompts before each input. This is useful
34 35 for making documentation, and in conjunction with -o, for producing
35 36 doctest-ready output.
36 37
37 38 -t: (default) print the 'translated' history, as IPython understands it.
38 39 IPython filters your input and converts it all into valid Python source
39 40 before executing it (things like magics or aliases are turned into
40 41 function calls, for example). With this option, you'll see the native
41 42 history instead of the user-entered version: '%cd /' will be seen as
42 43 '_ip.magic("%cd /")' instead of '%cd /'.
43 44
44 45 -r: print the 'raw' history, i.e. the actual commands you typed.
45 46
46 47 -g: treat the arg as a pattern to grep for in (full) history.
47 48 This includes the "shadow history" (almost all commands ever written).
48 49 Use '%hist -g' to show full shadow history (may be very long).
49 50 In shadow history, every index nuwber starts with 0.
50 51
51 52 -f FILENAME: instead of printing the output to the screen, redirect it to
52 53 the given file. The file is always overwritten, though IPython asks for
53 54 confirmation first if it already exists.
54 55 """
55 56
56 57 if not self.outputcache.do_full_cache:
57 58 print 'This feature is only available if numbered prompts are in use.'
58 59 return
59 60 opts,args = self.parse_options(parameter_s,'gnoptsrf:',mode='list')
60 61
61 62 # Check if output to specific file was requested.
62 63 try:
63 64 outfname = opts['f']
64 65 except KeyError:
65 outfile = Term.cout # default
66 outfile = IPython.utils.io.Term.cout # default
66 67 # We don't want to close stdout at the end!
67 68 close_at_end = False
68 69 else:
69 70 if os.path.exists(outfname):
70 71 if not ask_yes_no("File %r exists. Overwrite?" % outfname):
71 72 print 'Aborting.'
72 73 return
73 74
74 75 outfile = open(outfname,'w')
75 76 close_at_end = True
76 77
77 78 if 't' in opts:
78 79 input_hist = self.input_hist
79 80 elif 'r' in opts:
80 81 input_hist = self.input_hist_raw
81 82 else:
82 83 input_hist = self.input_hist
83 84
84 85 default_length = 40
85 86 pattern = None
86 87 if 'g' in opts:
87 88 init = 1
88 89 final = len(input_hist)
89 90 parts = parameter_s.split(None, 1)
90 91 if len(parts) == 1:
91 92 parts += '*'
92 93 head, pattern = parts
93 94 pattern = "*" + pattern + "*"
94 95 elif len(args) == 0:
95 96 final = len(input_hist)-1
96 97 init = max(1,final-default_length)
97 98 elif len(args) == 1:
98 99 final = len(input_hist)
99 100 init = max(1, final-int(args[0]))
100 101 elif len(args) == 2:
101 102 init, final = map(int, args)
102 103 else:
103 104 warn('%hist takes 0, 1 or 2 arguments separated by spaces.')
104 print >> Term.cout, self.magic_hist.__doc__
105 print >> IPython.utils.io.Term.cout, self.magic_hist.__doc__
105 106 return
106 107
107 108 width = len(str(final))
108 109 line_sep = ['','\n']
109 110 print_nums = 'n' in opts
110 111 print_outputs = 'o' in opts
111 112 pyprompts = 'p' in opts
112 113
113 114 found = False
114 115 if pattern is not None:
115 116 sh = self.shadowhist.all()
116 117 for idx, s in sh:
117 118 if fnmatch.fnmatch(s, pattern):
118 119 print >> outfile, "0%d: %s" %(idx, s)
119 120 found = True
120 121
121 122 if found:
122 123 print >> outfile, "==="
123 124 print >> outfile, \
124 125 "shadow history ends, fetch by %rep <number> (must start with 0)"
125 126 print >> outfile, "=== start of normal history ==="
126 127
127 128 for in_num in range(init,final):
128 129 inline = input_hist[in_num]
129 130 if pattern is not None and not fnmatch.fnmatch(inline, pattern):
130 131 continue
131 132
132 133 multiline = int(inline.count('\n') > 1)
133 134 if print_nums:
134 135 print >> outfile, \
135 136 '%s:%s' % (str(in_num).ljust(width), line_sep[multiline]),
136 137 if pyprompts:
137 138 print >> outfile, '>>>',
138 139 if multiline:
139 140 lines = inline.splitlines()
140 141 print >> outfile, '\n... '.join(lines)
141 142 print >> outfile, '... '
142 143 else:
143 144 print >> outfile, inline,
144 145 else:
145 146 print >> outfile, inline,
146 147 if print_outputs:
147 148 output = self.shell.user_ns['Out'].get(in_num)
148 149 if output is not None:
149 150 print >> outfile, repr(output)
150 151
151 152 if close_at_end:
152 153 outfile.close()
153 154
154 155
155 156 def magic_hist(self, parameter_s=''):
156 157 """Alternate name for %history."""
157 158 return self.magic_history(parameter_s)
158 159
159 160
160 161 def rep_f(self, arg):
161 162 r""" Repeat a command, or get command to input line for editing
162 163
163 164 - %rep (no arguments):
164 165
165 166 Place a string version of last computation result (stored in the special '_'
166 167 variable) to the next input prompt. Allows you to create elaborate command
167 168 lines without using copy-paste::
168 169
169 170 $ l = ["hei", "vaan"]
170 171 $ "".join(l)
171 172 ==> heivaan
172 173 $ %rep
173 174 $ heivaan_ <== cursor blinking
174 175
175 176 %rep 45
176 177
177 178 Place history line 45 to next input prompt. Use %hist to find out the
178 179 number.
179 180
180 181 %rep 1-4 6-7 3
181 182
182 183 Repeat the specified lines immediately. Input slice syntax is the same as
183 184 in %macro and %save.
184 185
185 186 %rep foo
186 187
187 188 Place the most recent line that has the substring "foo" to next input.
188 189 (e.g. 'svn ci -m foobar').
189 190 """
190 191
191 192 opts,args = self.parse_options(arg,'',mode='list')
192 193 if not args:
193 194 self.set_next_input(str(self.user_ns["_"]))
194 195 return
195 196
196 197 if len(args) == 1 and not '-' in args[0]:
197 198 arg = args[0]
198 199 if len(arg) > 1 and arg.startswith('0'):
199 200 # get from shadow hist
200 201 num = int(arg[1:])
201 202 line = self.shadowhist.get(num)
202 203 self.set_next_input(str(line))
203 204 return
204 205 try:
205 206 num = int(args[0])
206 207 self.set_next_input(str(self.input_hist_raw[num]).rstrip())
207 208 return
208 209 except ValueError:
209 210 pass
210 211
211 212 for h in reversed(self.input_hist_raw):
212 213 if 'rep' in h:
213 214 continue
214 215 if fnmatch.fnmatch(h,'*' + arg + '*'):
215 216 self.set_next_input(str(h).rstrip())
216 217 return
217 218
218 219 try:
219 220 lines = self.extract_input_slices(args, True)
220 221 print "lines",lines
221 222 self.runlines(lines)
222 223 except ValueError:
223 224 print "Not found in recent history:", args
224 225
225 226
226 227 _sentinel = object()
227 228
228 229 class ShadowHist(object):
229 230 def __init__(self,db):
230 231 # cmd => idx mapping
231 232 self.curidx = 0
232 233 self.db = db
233 234 self.disabled = False
234 235
235 236 def inc_idx(self):
236 237 idx = self.db.get('shadowhist_idx', 1)
237 238 self.db['shadowhist_idx'] = idx + 1
238 239 return idx
239 240
240 241 def add(self, ent):
241 242 if self.disabled:
242 243 return
243 244 try:
244 245 old = self.db.hget('shadowhist', ent, _sentinel)
245 246 if old is not _sentinel:
246 247 return
247 248 newidx = self.inc_idx()
248 249 #print "new",newidx # dbg
249 250 self.db.hset('shadowhist',ent, newidx)
250 251 except:
251 252 ipapi.get().showtraceback()
252 253 print "WARNING: disabling shadow history"
253 254 self.disabled = True
254 255
255 256 def all(self):
256 257 d = self.db.hdict('shadowhist')
257 258 items = [(i,s) for (s,i) in d.items()]
258 259 items.sort()
259 260 return items
260 261
261 262 def get(self, idx):
262 263 all = self.all()
263 264
264 265 for k, v in all:
265 266 #print k,v
266 267 if k == idx:
267 268 return v
268 269
269 270
270 271 def init_ipython(ip):
271 272 ip.define_magic("rep",rep_f)
272 273 ip.define_magic("hist",magic_hist)
273 274 ip.define_magic("history",magic_history)
274 275
275 276 # XXX - ipy_completers are in quarantine, need to be updated to new apis
276 277 #import ipy_completers
277 278 #ipy_completers.quick_completer('%hist' ,'-g -t -r -n')
@@ -1,276 +1,276 b''
1 1 """hooks for IPython.
2 2
3 3 In Python, it is possible to overwrite any method of any object if you really
4 4 want to. But IPython exposes a few 'hooks', methods which are _designed_ to
5 5 be overwritten by users for customization purposes. This module defines the
6 6 default versions of all such hooks, which get used by IPython if not
7 7 overridden by the user.
8 8
9 9 hooks are simple functions, but they should be declared with 'self' as their
10 10 first argument, because when activated they are registered into IPython as
11 11 instance methods. The self argument will be the IPython running instance
12 12 itself, so hooks have full access to the entire IPython object.
13 13
14 14 If you wish to define a new hook and activate it, you need to put the
15 15 necessary code into a python file which can be either imported or execfile()'d
16 16 from within your ipythonrc configuration.
17 17
18 18 For example, suppose that you have a module called 'myiphooks' in your
19 19 PYTHONPATH, which contains the following definition:
20 20
21 21 import os
22 22 from IPython.core import ipapi
23 23 ip = ipapi.get()
24 24
25 25 def calljed(self,filename, linenum):
26 26 "My editor hook calls the jed editor directly."
27 27 print "Calling my own editor, jed ..."
28 28 if os.system('jed +%d %s' % (linenum,filename)) != 0:
29 29 raise TryNext()
30 30
31 31 ip.set_hook('editor', calljed)
32 32
33 33 You can then enable the functionality by doing 'import myiphooks'
34 34 somewhere in your configuration files or ipython command line.
35 35 """
36 36
37 37 #*****************************************************************************
38 38 # Copyright (C) 2005 Fernando Perez. <fperez@colorado.edu>
39 39 #
40 40 # Distributed under the terms of the BSD License. The full license is in
41 41 # the file COPYING, distributed as part of this software.
42 42 #*****************************************************************************
43 43
44 44 import os, bisect
45 45 import sys
46 46
47 47 from pprint import PrettyPrinter
48 48
49 from IPython.utils.io import Term
49 import IPython.utils.io
50 50 from IPython.utils.process import shell
51 51
52 52 from IPython.core.error import TryNext
53 53
54 54 # List here all the default hooks. For now it's just the editor functions
55 55 # but over time we'll move here all the public API for user-accessible things.
56 56
57 57 __all__ = ['editor', 'fix_error_editor', 'synchronize_with_editor', 'result_display',
58 58 'input_prefilter', 'shutdown_hook', 'late_startup_hook',
59 59 'generate_prompt', 'generate_output_prompt','shell_hook',
60 60 'show_in_pager','pre_prompt_hook', 'pre_runcode_hook',
61 61 'clipboard_get']
62 62
63 63 pformat = PrettyPrinter().pformat
64 64
65 65 def editor(self,filename, linenum=None):
66 66 """Open the default editor at the given filename and linenumber.
67 67
68 68 This is IPython's default editor hook, you can use it as an example to
69 69 write your own modified one. To set your own editor function as the
70 70 new editor hook, call ip.set_hook('editor',yourfunc)."""
71 71
72 72 # IPython configures a default editor at startup by reading $EDITOR from
73 73 # the environment, and falling back on vi (unix) or notepad (win32).
74 74 editor = self.editor
75 75
76 76 # marker for at which line to open the file (for existing objects)
77 77 if linenum is None or editor=='notepad':
78 78 linemark = ''
79 79 else:
80 80 linemark = '+%d' % int(linenum)
81 81
82 82 # Enclose in quotes if necessary and legal
83 83 if ' ' in editor and os.path.isfile(editor) and editor[0] != '"':
84 84 editor = '"%s"' % editor
85 85
86 86 # Call the actual editor
87 87 if os.system('%s %s %s' % (editor,linemark,filename)) != 0:
88 88 raise TryNext()
89 89
90 90 import tempfile
91 91 def fix_error_editor(self,filename,linenum,column,msg):
92 92 """Open the editor at the given filename, linenumber, column and
93 93 show an error message. This is used for correcting syntax errors.
94 94 The current implementation only has special support for the VIM editor,
95 95 and falls back on the 'editor' hook if VIM is not used.
96 96
97 97 Call ip.set_hook('fix_error_editor',youfunc) to use your own function,
98 98 """
99 99 def vim_quickfix_file():
100 100 t = tempfile.NamedTemporaryFile()
101 101 t.write('%s:%d:%d:%s\n' % (filename,linenum,column,msg))
102 102 t.flush()
103 103 return t
104 104 if os.path.basename(self.editor) != 'vim':
105 105 self.hooks.editor(filename,linenum)
106 106 return
107 107 t = vim_quickfix_file()
108 108 try:
109 109 if os.system('vim --cmd "set errorformat=%f:%l:%c:%m" -q ' + t.name):
110 110 raise TryNext()
111 111 finally:
112 112 t.close()
113 113
114 114
115 115 def synchronize_with_editor(self, filename, linenum, column):
116 116 pass
117 117
118 118
119 119 class CommandChainDispatcher:
120 120 """ Dispatch calls to a chain of commands until some func can handle it
121 121
122 122 Usage: instantiate, execute "add" to add commands (with optional
123 123 priority), execute normally via f() calling mechanism.
124 124
125 125 """
126 126 def __init__(self,commands=None):
127 127 if commands is None:
128 128 self.chain = []
129 129 else:
130 130 self.chain = commands
131 131
132 132
133 133 def __call__(self,*args, **kw):
134 134 """ Command chain is called just like normal func.
135 135
136 136 This will call all funcs in chain with the same args as were given to this
137 137 function, and return the result of first func that didn't raise
138 138 TryNext """
139 139
140 140 for prio,cmd in self.chain:
141 141 #print "prio",prio,"cmd",cmd #dbg
142 142 try:
143 143 return cmd(*args, **kw)
144 144 except TryNext, exc:
145 145 if exc.args or exc.kwargs:
146 146 args = exc.args
147 147 kw = exc.kwargs
148 148 # if no function will accept it, raise TryNext up to the caller
149 149 raise TryNext
150 150
151 151 def __str__(self):
152 152 return str(self.chain)
153 153
154 154 def add(self, func, priority=0):
155 155 """ Add a func to the cmd chain with given priority """
156 156 bisect.insort(self.chain,(priority,func))
157 157
158 158 def __iter__(self):
159 159 """ Return all objects in chain.
160 160
161 161 Handy if the objects are not callable.
162 162 """
163 163 return iter(self.chain)
164 164
165 165
166 166 def result_display(self,arg):
167 167 """ Default display hook.
168 168
169 169 Called for displaying the result to the user.
170 170 """
171 171
172 172 if self.pprint:
173 173 out = pformat(arg)
174 174 if '\n' in out:
175 175 # So that multi-line strings line up with the left column of
176 176 # the screen, instead of having the output prompt mess up
177 177 # their first line.
178 Term.cout.write('\n')
179 print >>Term.cout, out
178 IPython.utils.io.Term.cout.write('\n')
179 print >>IPython.utils.io.Term.cout, out
180 180 else:
181 181 # By default, the interactive prompt uses repr() to display results,
182 182 # so we should honor this. Users who'd rather use a different
183 183 # mechanism can easily override this hook.
184 print >>Term.cout, repr(arg)
184 print >>IPython.utils.io.Term.cout, repr(arg)
185 185 # the default display hook doesn't manipulate the value to put in history
186 186 return None
187 187
188 188
189 189 def input_prefilter(self,line):
190 190 """ Default input prefilter
191 191
192 192 This returns the line as unchanged, so that the interpreter
193 193 knows that nothing was done and proceeds with "classic" prefiltering
194 194 (%magics, !shell commands etc.).
195 195
196 196 Note that leading whitespace is not passed to this hook. Prefilter
197 197 can't alter indentation.
198 198
199 199 """
200 200 #print "attempt to rewrite",line #dbg
201 201 return line
202 202
203 203
204 204 def shutdown_hook(self):
205 205 """ default shutdown hook
206 206
207 207 Typically, shotdown hooks should raise TryNext so all shutdown ops are done
208 208 """
209 209
210 210 #print "default shutdown hook ok" # dbg
211 211 return
212 212
213 213
214 214 def late_startup_hook(self):
215 215 """ Executed after ipython has been constructed and configured
216 216
217 217 """
218 218 #print "default startup hook ok" # dbg
219 219
220 220
221 221 def generate_prompt(self, is_continuation):
222 222 """ calculate and return a string with the prompt to display """
223 223 if is_continuation:
224 224 return str(self.outputcache.prompt2)
225 225 return str(self.outputcache.prompt1)
226 226
227 227
228 228 def generate_output_prompt(self):
229 229 return str(self.outputcache.prompt_out)
230 230
231 231
232 232 def shell_hook(self,cmd):
233 233 """ Run system/shell command a'la os.system() """
234 234
235 235 shell(cmd, header=self.system_header, verbose=self.system_verbose)
236 236
237 237
238 238 def show_in_pager(self,s):
239 239 """ Run a string through pager """
240 240 # raising TryNext here will use the default paging functionality
241 241 raise TryNext
242 242
243 243
244 244 def pre_prompt_hook(self):
245 245 """ Run before displaying the next prompt
246 246
247 247 Use this e.g. to display output from asynchronous operations (in order
248 248 to not mess up text entry)
249 249 """
250 250
251 251 return None
252 252
253 253
254 254 def pre_runcode_hook(self):
255 255 """ Executed before running the (prefiltered) code in IPython """
256 256 return None
257 257
258 258
259 259 def clipboard_get(self):
260 260 """ Get text from the clipboard.
261 261 """
262 262 from IPython.lib.clipboard import (
263 263 osx_clipboard_get, tkinter_clipboard_get,
264 264 win32_clipboard_get
265 265 )
266 266 if sys.platform == 'win32':
267 267 chain = [win32_clipboard_get, tkinter_clipboard_get]
268 268 elif sys.platform == 'darwin':
269 269 chain = [osx_clipboard_get, tkinter_clipboard_get]
270 270 else:
271 271 chain = [tkinter_clipboard_get]
272 272 dispatcher = CommandChainDispatcher()
273 273 for func in chain:
274 274 dispatcher.add(func)
275 275 text = dispatcher()
276 276 return text
@@ -1,2044 +1,2060 b''
1 1 # -*- coding: utf-8 -*-
2 2 """Main IPython class."""
3 3
4 4 #-----------------------------------------------------------------------------
5 5 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de>
6 6 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
7 7 # Copyright (C) 2008-2010 The IPython Development Team
8 8 #
9 9 # Distributed under the terms of the BSD License. The full license is in
10 10 # the file COPYING, distributed as part of this software.
11 11 #-----------------------------------------------------------------------------
12 12
13 13 #-----------------------------------------------------------------------------
14 14 # Imports
15 15 #-----------------------------------------------------------------------------
16 16
17 17 from __future__ import with_statement
18 18 from __future__ import absolute_import
19 19
20 20 import __builtin__
21 21 import abc
22 22 import codeop
23 23 import exceptions
24 24 import new
25 25 import os
26 26 import re
27 27 import string
28 28 import sys
29 29 import tempfile
30 30 from contextlib import nested
31 31
32 32 from IPython.core import debugger, oinspect
33 33 from IPython.core import history as ipcorehist
34 34 from IPython.core import prefilter
35 35 from IPython.core import shadowns
36 36 from IPython.core import ultratb
37 37 from IPython.core.alias import AliasManager
38 38 from IPython.core.builtin_trap import BuiltinTrap
39 39 from IPython.config.configurable import Configurable
40 40 from IPython.core.display_trap import DisplayTrap
41 41 from IPython.core.error import UsageError
42 42 from IPython.core.extensions import ExtensionManager
43 43 from IPython.core.fakemodule import FakeModule, init_fakemod_dict
44 44 from IPython.core.inputlist import InputList
45 45 from IPython.core.logger import Logger
46 46 from IPython.core.magic import Magic
47 47 from IPython.core.plugin import PluginManager
48 48 from IPython.core.prefilter import PrefilterManager
49 49 from IPython.core.prompts import CachedOutput
50 50 import IPython.core.hooks
51 51 from IPython.external.Itpl import ItplNS
52 52 from IPython.utils import PyColorize
53 53 from IPython.utils import pickleshare
54 54 from IPython.utils.doctestreload import doctest_reload
55 55 from IPython.utils.ipstruct import Struct
56 from IPython.utils.io import Term, ask_yes_no
56 import IPython.utils.io
57 from IPython.utils.io import ask_yes_no
57 58 from IPython.utils.path import get_home_dir, get_ipython_dir, HomeDirError
58 59 from IPython.utils.process import getoutput, getoutputerror
59 60 from IPython.utils.strdispatch import StrDispatch
60 61 from IPython.utils.syspathcontext import prepended_to_syspath
61 62 from IPython.utils.text import num_ini_spaces
62 63 from IPython.utils.warn import warn, error, fatal
63 64 from IPython.utils.traitlets import (
64 65 Int, Str, CBool, CaselessStrEnum, Enum, List, Unicode, Instance
65 66 )
66 67
67 68 # from IPython.utils import growl
68 69 # growl.start("IPython")
69 70
70 71 #-----------------------------------------------------------------------------
71 72 # Globals
72 73 #-----------------------------------------------------------------------------
73 74
74 75 # compiled regexps for autoindent management
75 76 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
76 77
77 78 #-----------------------------------------------------------------------------
78 79 # Utilities
79 80 #-----------------------------------------------------------------------------
80 81
81 82 # store the builtin raw_input globally, and use this always, in case user code
82 83 # overwrites it (like wx.py.PyShell does)
83 84 raw_input_original = raw_input
84 85
85 86 def softspace(file, newvalue):
86 87 """Copied from code.py, to remove the dependency"""
87 88
88 89 oldvalue = 0
89 90 try:
90 91 oldvalue = file.softspace
91 92 except AttributeError:
92 93 pass
93 94 try:
94 95 file.softspace = newvalue
95 96 except (AttributeError, TypeError):
96 97 # "attribute-less object" or "read-only attributes"
97 98 pass
98 99 return oldvalue
99 100
100 101
101 102 def no_op(*a, **kw): pass
102 103
103 104 class SpaceInInput(exceptions.Exception): pass
104 105
105 106 class Bunch: pass
106 107
107 108 class SyntaxTB(ultratb.ListTB):
108 109 """Extension which holds some state: the last exception value"""
109 110
110 111 def __init__(self,color_scheme = 'NoColor'):
111 112 ultratb.ListTB.__init__(self,color_scheme)
112 113 self.last_syntax_error = None
113 114
114 115 def __call__(self, etype, value, elist):
115 116 self.last_syntax_error = value
116 117 ultratb.ListTB.__call__(self,etype,value,elist)
117 118
118 119 def clear_err_state(self):
119 120 """Return the current error state and clear it"""
120 121 e = self.last_syntax_error
121 122 self.last_syntax_error = None
122 123 return e
123 124
124 125
125 126 def get_default_colors():
126 127 if sys.platform=='darwin':
127 128 return "LightBG"
128 129 elif os.name=='nt':
129 130 return 'Linux'
130 131 else:
131 132 return 'Linux'
132 133
133 134
134 135 class SeparateStr(Str):
135 136 """A Str subclass to validate separate_in, separate_out, etc.
136 137
137 138 This is a Str based trait that converts '0'->'' and '\\n'->'\n'.
138 139 """
139 140
140 141 def validate(self, obj, value):
141 142 if value == '0': value = ''
142 143 value = value.replace('\\n','\n')
143 144 return super(SeparateStr, self).validate(obj, value)
144 145
145 146
146 147 #-----------------------------------------------------------------------------
147 148 # Main IPython class
148 149 #-----------------------------------------------------------------------------
149 150
150 151
151 152 class InteractiveShell(Configurable, Magic):
152 153 """An enhanced, interactive shell for Python."""
153 154
154 155 autocall = Enum((0,1,2), default_value=1, config=True)
155 156 # TODO: remove all autoindent logic and put into frontends.
156 157 # We can't do this yet because even runlines uses the autoindent.
157 158 autoindent = CBool(True, config=True)
158 159 automagic = CBool(True, config=True)
159 160 cache_size = Int(1000, config=True)
160 161 color_info = CBool(True, config=True)
161 162 colors = CaselessStrEnum(('NoColor','LightBG','Linux'),
162 163 default_value=get_default_colors(), config=True)
163 164 debug = CBool(False, config=True)
164 165 deep_reload = CBool(False, config=True)
165 166 filename = Str("<ipython console>")
166 167 ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__
167 168 logstart = CBool(False, config=True)
168 169 logfile = Str('', config=True)
169 170 logappend = Str('', config=True)
170 171 object_info_string_level = Enum((0,1,2), default_value=0,
171 172 config=True)
172 173 pdb = CBool(False, config=True)
173 174 pprint = CBool(True, config=True)
174 175 profile = Str('', config=True)
175 176 prompt_in1 = Str('In [\\#]: ', config=True)
176 177 prompt_in2 = Str(' .\\D.: ', config=True)
177 178 prompt_out = Str('Out[\\#]: ', config=True)
178 179 prompts_pad_left = CBool(True, config=True)
179 180 quiet = CBool(False, config=True)
180 181
181 182 # The readline stuff will eventually be moved to the terminal subclass
182 183 # but for now, we can't do that as readline is welded in everywhere.
183 184 readline_use = CBool(True, config=True)
184 185 readline_merge_completions = CBool(True, config=True)
185 186 readline_omit__names = Enum((0,1,2), default_value=0, config=True)
186 187 readline_remove_delims = Str('-/~', config=True)
187 188 readline_parse_and_bind = List([
188 189 'tab: complete',
189 190 '"\C-l": clear-screen',
190 191 'set show-all-if-ambiguous on',
191 192 '"\C-o": tab-insert',
192 193 '"\M-i": " "',
193 194 '"\M-o": "\d\d\d\d"',
194 195 '"\M-I": "\d\d\d\d"',
195 196 '"\C-r": reverse-search-history',
196 197 '"\C-s": forward-search-history',
197 198 '"\C-p": history-search-backward',
198 199 '"\C-n": history-search-forward',
199 200 '"\e[A": history-search-backward',
200 201 '"\e[B": history-search-forward',
201 202 '"\C-k": kill-line',
202 203 '"\C-u": unix-line-discard',
203 204 ], allow_none=False, config=True)
204 205
205 206 # TODO: this part of prompt management should be moved to the frontends.
206 207 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
207 208 separate_in = SeparateStr('\n', config=True)
208 209 separate_out = SeparateStr('', config=True)
209 210 separate_out2 = SeparateStr('', config=True)
210 211 system_header = Str('IPython system call: ', config=True)
211 212 system_verbose = CBool(False, config=True)
212 213 wildcards_case_sensitive = CBool(True, config=True)
213 214 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
214 215 default_value='Context', config=True)
215 216
216 217 # Subcomponents of InteractiveShell
217 218 alias_manager = Instance('IPython.core.alias.AliasManager')
218 219 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
219 220 builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap')
220 221 display_trap = Instance('IPython.core.display_trap.DisplayTrap')
221 222 extension_manager = Instance('IPython.core.extensions.ExtensionManager')
222 223 plugin_manager = Instance('IPython.core.plugin.PluginManager')
223 224
224 225 def __init__(self, config=None, ipython_dir=None,
225 226 user_ns=None, user_global_ns=None,
226 227 custom_exceptions=((),None)):
227 228
228 229 # This is where traits with a config_key argument are updated
229 230 # from the values on config.
230 231 super(InteractiveShell, self).__init__(config=config)
231 232
232 233 # These are relatively independent and stateless
233 234 self.init_ipython_dir(ipython_dir)
234 235 self.init_instance_attrs()
235 236
236 237 # Create namespaces (user_ns, user_global_ns, etc.)
237 238 self.init_create_namespaces(user_ns, user_global_ns)
238 239 # This has to be done after init_create_namespaces because it uses
239 240 # something in self.user_ns, but before init_sys_modules, which
240 241 # is the first thing to modify sys.
241 242 self.save_sys_module_state()
242 243 self.init_sys_modules()
243 244
244 245 self.init_history()
245 246 self.init_encoding()
246 247 self.init_prefilter()
247 248
248 249 Magic.__init__(self, self)
249 250
250 251 self.init_syntax_highlighting()
251 252 self.init_hooks()
252 253 self.init_pushd_popd_magic()
254 # TODO: init_io() needs to happen before init_traceback handlers
255 # because the traceback handlers hardcode the stdout/stderr streams.
256 # This logic in in debugger.Pdb and should eventually be changed.
257 self.init_io()
253 258 self.init_traceback_handlers(custom_exceptions)
254 259 self.init_user_ns()
255 260 self.init_logger()
256 261 self.init_alias()
257 262 self.init_builtins()
258 263
259 264 # pre_config_initialization
260 265 self.init_shadow_hist()
261 266
262 267 # The next section should contain averything that was in ipmaker.
263 268 self.init_logstart()
264 269
265 270 # The following was in post_config_initialization
266 271 self.init_inspector()
267 272 self.init_readline()
268 273 self.init_prompts()
269 274 self.init_displayhook()
270 275 self.init_reload_doctest()
271 276 self.init_magics()
272 277 self.init_pdb()
273 278 self.init_extension_manager()
274 279 self.init_plugin_manager()
275 280 self.hooks.late_startup_hook()
276 281
277 282 @classmethod
278 283 def instance(cls, *args, **kwargs):
279 284 """Returns a global InteractiveShell instance."""
280 285 if not hasattr(cls, "_instance"):
281 286 cls._instance = cls(*args, **kwargs)
282 287 return cls._instance
283 288
284 289 @classmethod
285 290 def initialized(cls):
286 291 return hasattr(cls, "_instance")
287 292
288 293 def get_ipython(self):
289 294 """Return the currently running IPython instance."""
290 295 return self
291 296
292 297 #-------------------------------------------------------------------------
293 298 # Trait changed handlers
294 299 #-------------------------------------------------------------------------
295 300
296 301 def _ipython_dir_changed(self, name, new):
297 302 if not os.path.isdir(new):
298 303 os.makedirs(new, mode = 0777)
299 304
300 305 def set_autoindent(self,value=None):
301 306 """Set the autoindent flag, checking for readline support.
302 307
303 308 If called with no arguments, it acts as a toggle."""
304 309
305 310 if not self.has_readline:
306 311 if os.name == 'posix':
307 312 warn("The auto-indent feature requires the readline library")
308 313 self.autoindent = 0
309 314 return
310 315 if value is None:
311 316 self.autoindent = not self.autoindent
312 317 else:
313 318 self.autoindent = value
314 319
315 320 #-------------------------------------------------------------------------
316 321 # init_* methods called by __init__
317 322 #-------------------------------------------------------------------------
318 323
319 324 def init_ipython_dir(self, ipython_dir):
320 325 if ipython_dir is not None:
321 326 self.ipython_dir = ipython_dir
322 327 self.config.Global.ipython_dir = self.ipython_dir
323 328 return
324 329
325 330 if hasattr(self.config.Global, 'ipython_dir'):
326 331 self.ipython_dir = self.config.Global.ipython_dir
327 332 else:
328 333 self.ipython_dir = get_ipython_dir()
329 334
330 335 # All children can just read this
331 336 self.config.Global.ipython_dir = self.ipython_dir
332 337
333 338 def init_instance_attrs(self):
334 339 self.more = False
335 340
336 341 # command compiler
337 342 self.compile = codeop.CommandCompiler()
338 343
339 344 # User input buffer
340 345 self.buffer = []
341 346
342 347 # Make an empty namespace, which extension writers can rely on both
343 348 # existing and NEVER being used by ipython itself. This gives them a
344 349 # convenient location for storing additional information and state
345 350 # their extensions may require, without fear of collisions with other
346 351 # ipython names that may develop later.
347 352 self.meta = Struct()
348 353
349 354 # Object variable to store code object waiting execution. This is
350 355 # used mainly by the multithreaded shells, but it can come in handy in
351 356 # other situations. No need to use a Queue here, since it's a single
352 357 # item which gets cleared once run.
353 358 self.code_to_run = None
354 359
355 360 # Temporary files used for various purposes. Deleted at exit.
356 361 self.tempfiles = []
357 362
358 363 # Keep track of readline usage (later set by init_readline)
359 364 self.has_readline = False
360 365
361 366 # keep track of where we started running (mainly for crash post-mortem)
362 367 # This is not being used anywhere currently.
363 368 self.starting_dir = os.getcwd()
364 369
365 370 # Indentation management
366 371 self.indent_current_nsp = 0
367 372
368 373 def init_encoding(self):
369 374 # Get system encoding at startup time. Certain terminals (like Emacs
370 375 # under Win32 have it set to None, and we need to have a known valid
371 376 # encoding to use in the raw_input() method
372 377 try:
373 378 self.stdin_encoding = sys.stdin.encoding or 'ascii'
374 379 except AttributeError:
375 380 self.stdin_encoding = 'ascii'
376 381
377 382 def init_syntax_highlighting(self):
378 383 # Python source parser/formatter for syntax highlighting
379 384 pyformat = PyColorize.Parser().format
380 385 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
381 386
382 387 def init_pushd_popd_magic(self):
383 388 # for pushd/popd management
384 389 try:
385 390 self.home_dir = get_home_dir()
386 391 except HomeDirError, msg:
387 392 fatal(msg)
388 393
389 394 self.dir_stack = []
390 395
391 396 def init_logger(self):
392 397 self.logger = Logger(self, logfname='ipython_log.py', logmode='rotate')
393 398 # local shortcut, this is used a LOT
394 399 self.log = self.logger.log
395 400
396 401 def init_logstart(self):
397 402 if self.logappend:
398 403 self.magic_logstart(self.logappend + ' append')
399 404 elif self.logfile:
400 405 self.magic_logstart(self.logfile)
401 406 elif self.logstart:
402 407 self.magic_logstart()
403 408
404 409 def init_builtins(self):
405 410 self.builtin_trap = BuiltinTrap(shell=self)
406 411
407 412 def init_inspector(self):
408 413 # Object inspector
409 414 self.inspector = oinspect.Inspector(oinspect.InspectColors,
410 415 PyColorize.ANSICodeColors,
411 416 'NoColor',
412 417 self.object_info_string_level)
413 418
419 def init_io(self):
420 import IPython.utils.io
421 if sys.platform == 'win32' and readline.have_readline and \
422 self.readline_use:
423 Term = IPython.utils.io.IOTerm(
424 cout=readline._outputfile,cerr=readline._outputfile
425 )
426 else:
427 Term = IPython.utils.io.IOTerm()
428 IPython.utils.io.Term = Term
429
414 430 def init_prompts(self):
415 431 # Initialize cache, set in/out prompts and printing system
416 432 self.outputcache = CachedOutput(self,
417 433 self.cache_size,
418 434 self.pprint,
419 435 input_sep = self.separate_in,
420 436 output_sep = self.separate_out,
421 437 output_sep2 = self.separate_out2,
422 438 ps1 = self.prompt_in1,
423 439 ps2 = self.prompt_in2,
424 440 ps_out = self.prompt_out,
425 441 pad_left = self.prompts_pad_left)
426 442
427 443 # user may have over-ridden the default print hook:
428 444 try:
429 445 self.outputcache.__class__.display = self.hooks.display
430 446 except AttributeError:
431 447 pass
432 448
433 449 def init_displayhook(self):
434 450 self.display_trap = DisplayTrap(hook=self.outputcache)
435 451
436 452 def init_reload_doctest(self):
437 453 # Do a proper resetting of doctest, including the necessary displayhook
438 454 # monkeypatching
439 455 try:
440 456 doctest_reload()
441 457 except ImportError:
442 458 warn("doctest module does not exist.")
443 459
444 460 #-------------------------------------------------------------------------
445 461 # Things related to injections into the sys module
446 462 #-------------------------------------------------------------------------
447 463
448 464 def save_sys_module_state(self):
449 465 """Save the state of hooks in the sys module.
450 466
451 467 This has to be called after self.user_ns is created.
452 468 """
453 469 self._orig_sys_module_state = {}
454 470 self._orig_sys_module_state['stdin'] = sys.stdin
455 471 self._orig_sys_module_state['stdout'] = sys.stdout
456 472 self._orig_sys_module_state['stderr'] = sys.stderr
457 473 self._orig_sys_module_state['excepthook'] = sys.excepthook
458 474 try:
459 475 self._orig_sys_modules_main_name = self.user_ns['__name__']
460 476 except KeyError:
461 477 pass
462 478
463 479 def restore_sys_module_state(self):
464 480 """Restore the state of the sys module."""
465 481 try:
466 482 for k, v in self._orig_sys_module_state.items():
467 483 setattr(sys, k, v)
468 484 except AttributeError:
469 485 pass
470 486 try:
471 487 delattr(sys, 'ipcompleter')
472 488 except AttributeError:
473 489 pass
474 490 # Reset what what done in self.init_sys_modules
475 491 try:
476 492 sys.modules[self.user_ns['__name__']] = self._orig_sys_modules_main_name
477 493 except (AttributeError, KeyError):
478 494 pass
479 495
480 496 #-------------------------------------------------------------------------
481 497 # Things related to hooks
482 498 #-------------------------------------------------------------------------
483 499
484 500 def init_hooks(self):
485 501 # hooks holds pointers used for user-side customizations
486 502 self.hooks = Struct()
487 503
488 504 self.strdispatchers = {}
489 505
490 506 # Set all default hooks, defined in the IPython.hooks module.
491 507 hooks = IPython.core.hooks
492 508 for hook_name in hooks.__all__:
493 509 # default hooks have priority 100, i.e. low; user hooks should have
494 510 # 0-100 priority
495 511 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
496 512
497 513 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
498 514 """set_hook(name,hook) -> sets an internal IPython hook.
499 515
500 516 IPython exposes some of its internal API as user-modifiable hooks. By
501 517 adding your function to one of these hooks, you can modify IPython's
502 518 behavior to call at runtime your own routines."""
503 519
504 520 # At some point in the future, this should validate the hook before it
505 521 # accepts it. Probably at least check that the hook takes the number
506 522 # of args it's supposed to.
507 523
508 524 f = new.instancemethod(hook,self,self.__class__)
509 525
510 526 # check if the hook is for strdispatcher first
511 527 if str_key is not None:
512 528 sdp = self.strdispatchers.get(name, StrDispatch())
513 529 sdp.add_s(str_key, f, priority )
514 530 self.strdispatchers[name] = sdp
515 531 return
516 532 if re_key is not None:
517 533 sdp = self.strdispatchers.get(name, StrDispatch())
518 534 sdp.add_re(re.compile(re_key), f, priority )
519 535 self.strdispatchers[name] = sdp
520 536 return
521 537
522 538 dp = getattr(self.hooks, name, None)
523 539 if name not in IPython.core.hooks.__all__:
524 540 print "Warning! Hook '%s' is not one of %s" % (name, IPython.core.hooks.__all__ )
525 541 if not dp:
526 542 dp = IPython.core.hooks.CommandChainDispatcher()
527 543
528 544 try:
529 545 dp.add(f,priority)
530 546 except AttributeError:
531 547 # it was not commandchain, plain old func - replace
532 548 dp = f
533 549
534 550 setattr(self.hooks,name, dp)
535 551
536 552 #-------------------------------------------------------------------------
537 553 # Things related to the "main" module
538 554 #-------------------------------------------------------------------------
539 555
540 556 def new_main_mod(self,ns=None):
541 557 """Return a new 'main' module object for user code execution.
542 558 """
543 559 main_mod = self._user_main_module
544 560 init_fakemod_dict(main_mod,ns)
545 561 return main_mod
546 562
547 563 def cache_main_mod(self,ns,fname):
548 564 """Cache a main module's namespace.
549 565
550 566 When scripts are executed via %run, we must keep a reference to the
551 567 namespace of their __main__ module (a FakeModule instance) around so
552 568 that Python doesn't clear it, rendering objects defined therein
553 569 useless.
554 570
555 571 This method keeps said reference in a private dict, keyed by the
556 572 absolute path of the module object (which corresponds to the script
557 573 path). This way, for multiple executions of the same script we only
558 574 keep one copy of the namespace (the last one), thus preventing memory
559 575 leaks from old references while allowing the objects from the last
560 576 execution to be accessible.
561 577
562 578 Note: we can not allow the actual FakeModule instances to be deleted,
563 579 because of how Python tears down modules (it hard-sets all their
564 580 references to None without regard for reference counts). This method
565 581 must therefore make a *copy* of the given namespace, to allow the
566 582 original module's __dict__ to be cleared and reused.
567 583
568 584
569 585 Parameters
570 586 ----------
571 587 ns : a namespace (a dict, typically)
572 588
573 589 fname : str
574 590 Filename associated with the namespace.
575 591
576 592 Examples
577 593 --------
578 594
579 595 In [10]: import IPython
580 596
581 597 In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
582 598
583 599 In [12]: IPython.__file__ in _ip._main_ns_cache
584 600 Out[12]: True
585 601 """
586 602 self._main_ns_cache[os.path.abspath(fname)] = ns.copy()
587 603
588 604 def clear_main_mod_cache(self):
589 605 """Clear the cache of main modules.
590 606
591 607 Mainly for use by utilities like %reset.
592 608
593 609 Examples
594 610 --------
595 611
596 612 In [15]: import IPython
597 613
598 614 In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
599 615
600 616 In [17]: len(_ip._main_ns_cache) > 0
601 617 Out[17]: True
602 618
603 619 In [18]: _ip.clear_main_mod_cache()
604 620
605 621 In [19]: len(_ip._main_ns_cache) == 0
606 622 Out[19]: True
607 623 """
608 624 self._main_ns_cache.clear()
609 625
610 626 #-------------------------------------------------------------------------
611 627 # Things related to debugging
612 628 #-------------------------------------------------------------------------
613 629
614 630 def init_pdb(self):
615 631 # Set calling of pdb on exceptions
616 632 # self.call_pdb is a property
617 633 self.call_pdb = self.pdb
618 634
619 635 def _get_call_pdb(self):
620 636 return self._call_pdb
621 637
622 638 def _set_call_pdb(self,val):
623 639
624 640 if val not in (0,1,False,True):
625 641 raise ValueError,'new call_pdb value must be boolean'
626 642
627 643 # store value in instance
628 644 self._call_pdb = val
629 645
630 646 # notify the actual exception handlers
631 647 self.InteractiveTB.call_pdb = val
632 648
633 649 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
634 650 'Control auto-activation of pdb at exceptions')
635 651
636 652 def debugger(self,force=False):
637 653 """Call the pydb/pdb debugger.
638 654
639 655 Keywords:
640 656
641 657 - force(False): by default, this routine checks the instance call_pdb
642 658 flag and does not actually invoke the debugger if the flag is false.
643 659 The 'force' option forces the debugger to activate even if the flag
644 660 is false.
645 661 """
646 662
647 663 if not (force or self.call_pdb):
648 664 return
649 665
650 666 if not hasattr(sys,'last_traceback'):
651 667 error('No traceback has been produced, nothing to debug.')
652 668 return
653 669
654 670 # use pydb if available
655 671 if debugger.has_pydb:
656 672 from pydb import pm
657 673 else:
658 674 # fallback to our internal debugger
659 675 pm = lambda : self.InteractiveTB.debugger(force=True)
660 676 self.history_saving_wrapper(pm)()
661 677
662 678 #-------------------------------------------------------------------------
663 679 # Things related to IPython's various namespaces
664 680 #-------------------------------------------------------------------------
665 681
666 682 def init_create_namespaces(self, user_ns=None, user_global_ns=None):
667 683 # Create the namespace where the user will operate. user_ns is
668 684 # normally the only one used, and it is passed to the exec calls as
669 685 # the locals argument. But we do carry a user_global_ns namespace
670 686 # given as the exec 'globals' argument, This is useful in embedding
671 687 # situations where the ipython shell opens in a context where the
672 688 # distinction between locals and globals is meaningful. For
673 689 # non-embedded contexts, it is just the same object as the user_ns dict.
674 690
675 691 # FIXME. For some strange reason, __builtins__ is showing up at user
676 692 # level as a dict instead of a module. This is a manual fix, but I
677 693 # should really track down where the problem is coming from. Alex
678 694 # Schmolck reported this problem first.
679 695
680 696 # A useful post by Alex Martelli on this topic:
681 697 # Re: inconsistent value from __builtins__
682 698 # Von: Alex Martelli <aleaxit@yahoo.com>
683 699 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
684 700 # Gruppen: comp.lang.python
685 701
686 702 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
687 703 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
688 704 # > <type 'dict'>
689 705 # > >>> print type(__builtins__)
690 706 # > <type 'module'>
691 707 # > Is this difference in return value intentional?
692 708
693 709 # Well, it's documented that '__builtins__' can be either a dictionary
694 710 # or a module, and it's been that way for a long time. Whether it's
695 711 # intentional (or sensible), I don't know. In any case, the idea is
696 712 # that if you need to access the built-in namespace directly, you
697 713 # should start with "import __builtin__" (note, no 's') which will
698 714 # definitely give you a module. Yeah, it's somewhat confusing:-(.
699 715
700 716 # These routines return properly built dicts as needed by the rest of
701 717 # the code, and can also be used by extension writers to generate
702 718 # properly initialized namespaces.
703 719 user_ns, user_global_ns = self.make_user_namespaces(user_ns, user_global_ns)
704 720
705 721 # Assign namespaces
706 722 # This is the namespace where all normal user variables live
707 723 self.user_ns = user_ns
708 724 self.user_global_ns = user_global_ns
709 725
710 726 # An auxiliary namespace that checks what parts of the user_ns were
711 727 # loaded at startup, so we can list later only variables defined in
712 728 # actual interactive use. Since it is always a subset of user_ns, it
713 729 # doesn't need to be separately tracked in the ns_table.
714 730 self.user_ns_hidden = {}
715 731
716 732 # A namespace to keep track of internal data structures to prevent
717 733 # them from cluttering user-visible stuff. Will be updated later
718 734 self.internal_ns = {}
719 735
720 736 # Now that FakeModule produces a real module, we've run into a nasty
721 737 # problem: after script execution (via %run), the module where the user
722 738 # code ran is deleted. Now that this object is a true module (needed
723 739 # so docetst and other tools work correctly), the Python module
724 740 # teardown mechanism runs over it, and sets to None every variable
725 741 # present in that module. Top-level references to objects from the
726 742 # script survive, because the user_ns is updated with them. However,
727 743 # calling functions defined in the script that use other things from
728 744 # the script will fail, because the function's closure had references
729 745 # to the original objects, which are now all None. So we must protect
730 746 # these modules from deletion by keeping a cache.
731 747 #
732 748 # To avoid keeping stale modules around (we only need the one from the
733 749 # last run), we use a dict keyed with the full path to the script, so
734 750 # only the last version of the module is held in the cache. Note,
735 751 # however, that we must cache the module *namespace contents* (their
736 752 # __dict__). Because if we try to cache the actual modules, old ones
737 753 # (uncached) could be destroyed while still holding references (such as
738 754 # those held by GUI objects that tend to be long-lived)>
739 755 #
740 756 # The %reset command will flush this cache. See the cache_main_mod()
741 757 # and clear_main_mod_cache() methods for details on use.
742 758
743 759 # This is the cache used for 'main' namespaces
744 760 self._main_ns_cache = {}
745 761 # And this is the single instance of FakeModule whose __dict__ we keep
746 762 # copying and clearing for reuse on each %run
747 763 self._user_main_module = FakeModule()
748 764
749 765 # A table holding all the namespaces IPython deals with, so that
750 766 # introspection facilities can search easily.
751 767 self.ns_table = {'user':user_ns,
752 768 'user_global':user_global_ns,
753 769 'internal':self.internal_ns,
754 770 'builtin':__builtin__.__dict__
755 771 }
756 772
757 773 # Similarly, track all namespaces where references can be held and that
758 774 # we can safely clear (so it can NOT include builtin). This one can be
759 775 # a simple list.
760 776 self.ns_refs_table = [ user_ns, user_global_ns, self.user_ns_hidden,
761 777 self.internal_ns, self._main_ns_cache ]
762 778
763 779 def make_user_namespaces(self, user_ns=None, user_global_ns=None):
764 780 """Return a valid local and global user interactive namespaces.
765 781
766 782 This builds a dict with the minimal information needed to operate as a
767 783 valid IPython user namespace, which you can pass to the various
768 784 embedding classes in ipython. The default implementation returns the
769 785 same dict for both the locals and the globals to allow functions to
770 786 refer to variables in the namespace. Customized implementations can
771 787 return different dicts. The locals dictionary can actually be anything
772 788 following the basic mapping protocol of a dict, but the globals dict
773 789 must be a true dict, not even a subclass. It is recommended that any
774 790 custom object for the locals namespace synchronize with the globals
775 791 dict somehow.
776 792
777 793 Raises TypeError if the provided globals namespace is not a true dict.
778 794
779 795 Parameters
780 796 ----------
781 797 user_ns : dict-like, optional
782 798 The current user namespace. The items in this namespace should
783 799 be included in the output. If None, an appropriate blank
784 800 namespace should be created.
785 801 user_global_ns : dict, optional
786 802 The current user global namespace. The items in this namespace
787 803 should be included in the output. If None, an appropriate
788 804 blank namespace should be created.
789 805
790 806 Returns
791 807 -------
792 808 A pair of dictionary-like object to be used as the local namespace
793 809 of the interpreter and a dict to be used as the global namespace.
794 810 """
795 811
796 812
797 813 # We must ensure that __builtin__ (without the final 's') is always
798 814 # available and pointing to the __builtin__ *module*. For more details:
799 815 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
800 816
801 817 if user_ns is None:
802 818 # Set __name__ to __main__ to better match the behavior of the
803 819 # normal interpreter.
804 820 user_ns = {'__name__' :'__main__',
805 821 '__builtin__' : __builtin__,
806 822 '__builtins__' : __builtin__,
807 823 }
808 824 else:
809 825 user_ns.setdefault('__name__','__main__')
810 826 user_ns.setdefault('__builtin__',__builtin__)
811 827 user_ns.setdefault('__builtins__',__builtin__)
812 828
813 829 if user_global_ns is None:
814 830 user_global_ns = user_ns
815 831 if type(user_global_ns) is not dict:
816 832 raise TypeError("user_global_ns must be a true dict; got %r"
817 833 % type(user_global_ns))
818 834
819 835 return user_ns, user_global_ns
820 836
821 837 def init_sys_modules(self):
822 838 # We need to insert into sys.modules something that looks like a
823 839 # module but which accesses the IPython namespace, for shelve and
824 840 # pickle to work interactively. Normally they rely on getting
825 841 # everything out of __main__, but for embedding purposes each IPython
826 842 # instance has its own private namespace, so we can't go shoving
827 843 # everything into __main__.
828 844
829 845 # note, however, that we should only do this for non-embedded
830 846 # ipythons, which really mimic the __main__.__dict__ with their own
831 847 # namespace. Embedded instances, on the other hand, should not do
832 848 # this because they need to manage the user local/global namespaces
833 849 # only, but they live within a 'normal' __main__ (meaning, they
834 850 # shouldn't overtake the execution environment of the script they're
835 851 # embedded in).
836 852
837 853 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
838 854
839 855 try:
840 856 main_name = self.user_ns['__name__']
841 857 except KeyError:
842 858 raise KeyError('user_ns dictionary MUST have a "__name__" key')
843 859 else:
844 860 sys.modules[main_name] = FakeModule(self.user_ns)
845 861
846 862 def init_user_ns(self):
847 863 """Initialize all user-visible namespaces to their minimum defaults.
848 864
849 865 Certain history lists are also initialized here, as they effectively
850 866 act as user namespaces.
851 867
852 868 Notes
853 869 -----
854 870 All data structures here are only filled in, they are NOT reset by this
855 871 method. If they were not empty before, data will simply be added to
856 872 therm.
857 873 """
858 874 # This function works in two parts: first we put a few things in
859 875 # user_ns, and we sync that contents into user_ns_hidden so that these
860 876 # initial variables aren't shown by %who. After the sync, we add the
861 877 # rest of what we *do* want the user to see with %who even on a new
862 878 # session (probably nothing, so theye really only see their own stuff)
863 879
864 880 # The user dict must *always* have a __builtin__ reference to the
865 881 # Python standard __builtin__ namespace, which must be imported.
866 882 # This is so that certain operations in prompt evaluation can be
867 883 # reliably executed with builtins. Note that we can NOT use
868 884 # __builtins__ (note the 's'), because that can either be a dict or a
869 885 # module, and can even mutate at runtime, depending on the context
870 886 # (Python makes no guarantees on it). In contrast, __builtin__ is
871 887 # always a module object, though it must be explicitly imported.
872 888
873 889 # For more details:
874 890 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
875 891 ns = dict(__builtin__ = __builtin__)
876 892
877 893 # Put 'help' in the user namespace
878 894 try:
879 895 from site import _Helper
880 896 ns['help'] = _Helper()
881 897 except ImportError:
882 898 warn('help() not available - check site.py')
883 899
884 900 # make global variables for user access to the histories
885 901 ns['_ih'] = self.input_hist
886 902 ns['_oh'] = self.output_hist
887 903 ns['_dh'] = self.dir_hist
888 904
889 905 ns['_sh'] = shadowns
890 906
891 907 # user aliases to input and output histories. These shouldn't show up
892 908 # in %who, as they can have very large reprs.
893 909 ns['In'] = self.input_hist
894 910 ns['Out'] = self.output_hist
895 911
896 912 # Store myself as the public api!!!
897 913 ns['get_ipython'] = self.get_ipython
898 914
899 915 # Sync what we've added so far to user_ns_hidden so these aren't seen
900 916 # by %who
901 917 self.user_ns_hidden.update(ns)
902 918
903 919 # Anything put into ns now would show up in %who. Think twice before
904 920 # putting anything here, as we really want %who to show the user their
905 921 # stuff, not our variables.
906 922
907 923 # Finally, update the real user's namespace
908 924 self.user_ns.update(ns)
909 925
910 926
911 927 def reset(self):
912 928 """Clear all internal namespaces.
913 929
914 930 Note that this is much more aggressive than %reset, since it clears
915 931 fully all namespaces, as well as all input/output lists.
916 932 """
917 933 for ns in self.ns_refs_table:
918 934 ns.clear()
919 935
920 936 self.alias_manager.clear_aliases()
921 937
922 938 # Clear input and output histories
923 939 self.input_hist[:] = []
924 940 self.input_hist_raw[:] = []
925 941 self.output_hist.clear()
926 942
927 943 # Restore the user namespaces to minimal usability
928 944 self.init_user_ns()
929 945
930 946 # Restore the default and user aliases
931 947 self.alias_manager.init_aliases()
932 948
933 949 def reset_selective(self, regex=None):
934 950 """Clear selective variables from internal namespaces based on a specified regular expression.
935 951
936 952 Parameters
937 953 ----------
938 954 regex : string or compiled pattern, optional
939 955 A regular expression pattern that will be used in searching variable names in the users
940 956 namespaces.
941 957 """
942 958 if regex is not None:
943 959 try:
944 960 m = re.compile(regex)
945 961 except TypeError:
946 962 raise TypeError('regex must be a string or compiled pattern')
947 963 # Search for keys in each namespace that match the given regex
948 964 # If a match is found, delete the key/value pair.
949 965 for ns in self.ns_refs_table:
950 966 for var in ns:
951 967 if m.search(var):
952 968 del ns[var]
953 969
954 970 def push(self, variables, interactive=True):
955 971 """Inject a group of variables into the IPython user namespace.
956 972
957 973 Parameters
958 974 ----------
959 975 variables : dict, str or list/tuple of str
960 976 The variables to inject into the user's namespace. If a dict,
961 977 a simple update is done. If a str, the string is assumed to
962 978 have variable names separated by spaces. A list/tuple of str
963 979 can also be used to give the variable names. If just the variable
964 980 names are give (list/tuple/str) then the variable values looked
965 981 up in the callers frame.
966 982 interactive : bool
967 983 If True (default), the variables will be listed with the ``who``
968 984 magic.
969 985 """
970 986 vdict = None
971 987
972 988 # We need a dict of name/value pairs to do namespace updates.
973 989 if isinstance(variables, dict):
974 990 vdict = variables
975 991 elif isinstance(variables, (basestring, list, tuple)):
976 992 if isinstance(variables, basestring):
977 993 vlist = variables.split()
978 994 else:
979 995 vlist = variables
980 996 vdict = {}
981 997 cf = sys._getframe(1)
982 998 for name in vlist:
983 999 try:
984 1000 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
985 1001 except:
986 1002 print ('Could not get variable %s from %s' %
987 1003 (name,cf.f_code.co_name))
988 1004 else:
989 1005 raise ValueError('variables must be a dict/str/list/tuple')
990 1006
991 1007 # Propagate variables to user namespace
992 1008 self.user_ns.update(vdict)
993 1009
994 1010 # And configure interactive visibility
995 1011 config_ns = self.user_ns_hidden
996 1012 if interactive:
997 1013 for name, val in vdict.iteritems():
998 1014 config_ns.pop(name, None)
999 1015 else:
1000 1016 for name,val in vdict.iteritems():
1001 1017 config_ns[name] = val
1002 1018
1003 1019 #-------------------------------------------------------------------------
1004 1020 # Things related to history management
1005 1021 #-------------------------------------------------------------------------
1006 1022
1007 1023 def init_history(self):
1008 1024 # List of input with multi-line handling.
1009 1025 self.input_hist = InputList()
1010 1026 # This one will hold the 'raw' input history, without any
1011 1027 # pre-processing. This will allow users to retrieve the input just as
1012 1028 # it was exactly typed in by the user, with %hist -r.
1013 1029 self.input_hist_raw = InputList()
1014 1030
1015 1031 # list of visited directories
1016 1032 try:
1017 1033 self.dir_hist = [os.getcwd()]
1018 1034 except OSError:
1019 1035 self.dir_hist = []
1020 1036
1021 1037 # dict of output history
1022 1038 self.output_hist = {}
1023 1039
1024 1040 # Now the history file
1025 1041 if self.profile:
1026 1042 histfname = 'history-%s' % self.profile
1027 1043 else:
1028 1044 histfname = 'history'
1029 1045 self.histfile = os.path.join(self.ipython_dir, histfname)
1030 1046
1031 1047 # Fill the history zero entry, user counter starts at 1
1032 1048 self.input_hist.append('\n')
1033 1049 self.input_hist_raw.append('\n')
1034 1050
1035 1051 def init_shadow_hist(self):
1036 1052 try:
1037 1053 self.db = pickleshare.PickleShareDB(self.ipython_dir + "/db")
1038 1054 except exceptions.UnicodeDecodeError:
1039 1055 print "Your ipython_dir can't be decoded to unicode!"
1040 1056 print "Please set HOME environment variable to something that"
1041 1057 print r"only has ASCII characters, e.g. c:\home"
1042 1058 print "Now it is", self.ipython_dir
1043 1059 sys.exit()
1044 1060 self.shadowhist = ipcorehist.ShadowHist(self.db)
1045 1061
1046 1062 def savehist(self):
1047 1063 """Save input history to a file (via readline library)."""
1048 1064
1049 1065 try:
1050 1066 self.readline.write_history_file(self.histfile)
1051 1067 except:
1052 1068 print 'Unable to save IPython command history to file: ' + \
1053 1069 `self.histfile`
1054 1070
1055 1071 def reloadhist(self):
1056 1072 """Reload the input history from disk file."""
1057 1073
1058 1074 try:
1059 1075 self.readline.clear_history()
1060 1076 self.readline.read_history_file(self.shell.histfile)
1061 1077 except AttributeError:
1062 1078 pass
1063 1079
1064 1080 def history_saving_wrapper(self, func):
1065 1081 """ Wrap func for readline history saving
1066 1082
1067 1083 Convert func into callable that saves & restores
1068 1084 history around the call """
1069 1085
1070 1086 if self.has_readline:
1071 1087 from IPython.utils import rlineimpl as readline
1072 1088 else:
1073 1089 return func
1074 1090
1075 1091 def wrapper():
1076 1092 self.savehist()
1077 1093 try:
1078 1094 func()
1079 1095 finally:
1080 1096 readline.read_history_file(self.histfile)
1081 1097 return wrapper
1082 1098
1083 1099 #-------------------------------------------------------------------------
1084 1100 # Things related to exception handling and tracebacks (not debugging)
1085 1101 #-------------------------------------------------------------------------
1086 1102
1087 1103 def init_traceback_handlers(self, custom_exceptions):
1088 1104 # Syntax error handler.
1089 1105 self.SyntaxTB = SyntaxTB(color_scheme='NoColor')
1090 1106
1091 1107 # The interactive one is initialized with an offset, meaning we always
1092 1108 # want to remove the topmost item in the traceback, which is our own
1093 1109 # internal code. Valid modes: ['Plain','Context','Verbose']
1094 1110 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1095 1111 color_scheme='NoColor',
1096 1112 tb_offset = 1)
1097 1113
1098 1114 # The instance will store a pointer to the system-wide exception hook,
1099 1115 # so that runtime code (such as magics) can access it. This is because
1100 1116 # during the read-eval loop, it may get temporarily overwritten.
1101 1117 self.sys_excepthook = sys.excepthook
1102 1118
1103 1119 # and add any custom exception handlers the user may have specified
1104 1120 self.set_custom_exc(*custom_exceptions)
1105 1121
1106 1122 # Set the exception mode
1107 1123 self.InteractiveTB.set_mode(mode=self.xmode)
1108 1124
1109 1125 def set_custom_exc(self,exc_tuple,handler):
1110 1126 """set_custom_exc(exc_tuple,handler)
1111 1127
1112 1128 Set a custom exception handler, which will be called if any of the
1113 1129 exceptions in exc_tuple occur in the mainloop (specifically, in the
1114 1130 runcode() method.
1115 1131
1116 1132 Inputs:
1117 1133
1118 1134 - exc_tuple: a *tuple* of valid exceptions to call the defined
1119 1135 handler for. It is very important that you use a tuple, and NOT A
1120 1136 LIST here, because of the way Python's except statement works. If
1121 1137 you only want to trap a single exception, use a singleton tuple:
1122 1138
1123 1139 exc_tuple == (MyCustomException,)
1124 1140
1125 1141 - handler: this must be defined as a function with the following
1126 1142 basic interface: def my_handler(self,etype,value,tb).
1127 1143
1128 1144 This will be made into an instance method (via new.instancemethod)
1129 1145 of IPython itself, and it will be called if any of the exceptions
1130 1146 listed in the exc_tuple are caught. If the handler is None, an
1131 1147 internal basic one is used, which just prints basic info.
1132 1148
1133 1149 WARNING: by putting in your own exception handler into IPython's main
1134 1150 execution loop, you run a very good chance of nasty crashes. This
1135 1151 facility should only be used if you really know what you are doing."""
1136 1152
1137 1153 assert type(exc_tuple)==type(()) , \
1138 1154 "The custom exceptions must be given AS A TUPLE."
1139 1155
1140 1156 def dummy_handler(self,etype,value,tb):
1141 1157 print '*** Simple custom exception handler ***'
1142 1158 print 'Exception type :',etype
1143 1159 print 'Exception value:',value
1144 1160 print 'Traceback :',tb
1145 1161 print 'Source code :','\n'.join(self.buffer)
1146 1162
1147 1163 if handler is None: handler = dummy_handler
1148 1164
1149 1165 self.CustomTB = new.instancemethod(handler,self,self.__class__)
1150 1166 self.custom_exceptions = exc_tuple
1151 1167
1152 1168 def excepthook(self, etype, value, tb):
1153 1169 """One more defense for GUI apps that call sys.excepthook.
1154 1170
1155 1171 GUI frameworks like wxPython trap exceptions and call
1156 1172 sys.excepthook themselves. I guess this is a feature that
1157 1173 enables them to keep running after exceptions that would
1158 1174 otherwise kill their mainloop. This is a bother for IPython
1159 1175 which excepts to catch all of the program exceptions with a try:
1160 1176 except: statement.
1161 1177
1162 1178 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1163 1179 any app directly invokes sys.excepthook, it will look to the user like
1164 1180 IPython crashed. In order to work around this, we can disable the
1165 1181 CrashHandler and replace it with this excepthook instead, which prints a
1166 1182 regular traceback using our InteractiveTB. In this fashion, apps which
1167 1183 call sys.excepthook will generate a regular-looking exception from
1168 1184 IPython, and the CrashHandler will only be triggered by real IPython
1169 1185 crashes.
1170 1186
1171 1187 This hook should be used sparingly, only in places which are not likely
1172 1188 to be true IPython errors.
1173 1189 """
1174 1190 self.showtraceback((etype,value,tb),tb_offset=0)
1175 1191
1176 1192 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None,
1177 1193 exception_only=False):
1178 1194 """Display the exception that just occurred.
1179 1195
1180 1196 If nothing is known about the exception, this is the method which
1181 1197 should be used throughout the code for presenting user tracebacks,
1182 1198 rather than directly invoking the InteractiveTB object.
1183 1199
1184 1200 A specific showsyntaxerror() also exists, but this method can take
1185 1201 care of calling it if needed, so unless you are explicitly catching a
1186 1202 SyntaxError exception, don't try to analyze the stack manually and
1187 1203 simply call this method."""
1188 1204
1189 1205 try:
1190 1206 if exc_tuple is None:
1191 1207 etype, value, tb = sys.exc_info()
1192 1208 else:
1193 1209 etype, value, tb = exc_tuple
1194 1210
1195 1211 if etype is None:
1196 1212 if hasattr(sys, 'last_type'):
1197 1213 etype, value, tb = sys.last_type, sys.last_value, \
1198 1214 sys.last_traceback
1199 1215 else:
1200 1216 self.write('No traceback available to show.\n')
1201 1217 return
1202 1218
1203 1219 if etype is SyntaxError:
1204 1220 # Though this won't be called by syntax errors in the input
1205 1221 # line, there may be SyntaxError cases whith imported code.
1206 1222 self.showsyntaxerror(filename)
1207 1223 elif etype is UsageError:
1208 1224 print "UsageError:", value
1209 1225 else:
1210 1226 # WARNING: these variables are somewhat deprecated and not
1211 1227 # necessarily safe to use in a threaded environment, but tools
1212 1228 # like pdb depend on their existence, so let's set them. If we
1213 1229 # find problems in the field, we'll need to revisit their use.
1214 1230 sys.last_type = etype
1215 1231 sys.last_value = value
1216 1232 sys.last_traceback = tb
1217 1233
1218 1234 if etype in self.custom_exceptions:
1219 1235 self.CustomTB(etype,value,tb)
1220 1236 else:
1221 1237 if exception_only:
1222 1238 m = ('An exception has occurred, use %tb to see the '
1223 1239 'full traceback.')
1224 1240 print m
1225 1241 self.InteractiveTB.show_exception_only(etype, value)
1226 1242 else:
1227 1243 self.InteractiveTB(etype,value,tb,tb_offset=tb_offset)
1228 1244 if self.InteractiveTB.call_pdb:
1229 1245 # pdb mucks up readline, fix it back
1230 1246 self.set_completer()
1231 1247
1232 1248 except KeyboardInterrupt:
1233 1249 self.write("\nKeyboardInterrupt\n")
1234 1250
1235 1251
1236 1252 def showsyntaxerror(self, filename=None):
1237 1253 """Display the syntax error that just occurred.
1238 1254
1239 1255 This doesn't display a stack trace because there isn't one.
1240 1256
1241 1257 If a filename is given, it is stuffed in the exception instead
1242 1258 of what was there before (because Python's parser always uses
1243 1259 "<string>" when reading from a string).
1244 1260 """
1245 1261 etype, value, last_traceback = sys.exc_info()
1246 1262
1247 1263 # See note about these variables in showtraceback() above
1248 1264 sys.last_type = etype
1249 1265 sys.last_value = value
1250 1266 sys.last_traceback = last_traceback
1251 1267
1252 1268 if filename and etype is SyntaxError:
1253 1269 # Work hard to stuff the correct filename in the exception
1254 1270 try:
1255 1271 msg, (dummy_filename, lineno, offset, line) = value
1256 1272 except:
1257 1273 # Not the format we expect; leave it alone
1258 1274 pass
1259 1275 else:
1260 1276 # Stuff in the right filename
1261 1277 try:
1262 1278 # Assume SyntaxError is a class exception
1263 1279 value = SyntaxError(msg, (filename, lineno, offset, line))
1264 1280 except:
1265 1281 # If that failed, assume SyntaxError is a string
1266 1282 value = msg, (filename, lineno, offset, line)
1267 1283 self.SyntaxTB(etype,value,[])
1268 1284
1269 1285 #-------------------------------------------------------------------------
1270 1286 # Things related to tab completion
1271 1287 #-------------------------------------------------------------------------
1272 1288
1273 1289 def complete(self, text):
1274 1290 """Return a sorted list of all possible completions on text.
1275 1291
1276 1292 Inputs:
1277 1293
1278 1294 - text: a string of text to be completed on.
1279 1295
1280 1296 This is a wrapper around the completion mechanism, similar to what
1281 1297 readline does at the command line when the TAB key is hit. By
1282 1298 exposing it as a method, it can be used by other non-readline
1283 1299 environments (such as GUIs) for text completion.
1284 1300
1285 1301 Simple usage example:
1286 1302
1287 1303 In [7]: x = 'hello'
1288 1304
1289 1305 In [8]: x
1290 1306 Out[8]: 'hello'
1291 1307
1292 1308 In [9]: print x
1293 1309 hello
1294 1310
1295 1311 In [10]: _ip.complete('x.l')
1296 1312 Out[10]: ['x.ljust', 'x.lower', 'x.lstrip']
1297 1313 """
1298 1314
1299 1315 # Inject names into __builtin__ so we can complete on the added names.
1300 1316 with self.builtin_trap:
1301 1317 complete = self.Completer.complete
1302 1318 state = 0
1303 1319 # use a dict so we get unique keys, since ipyhton's multiple
1304 1320 # completers can return duplicates. When we make 2.4 a requirement,
1305 1321 # start using sets instead, which are faster.
1306 1322 comps = {}
1307 1323 while True:
1308 1324 newcomp = complete(text,state,line_buffer=text)
1309 1325 if newcomp is None:
1310 1326 break
1311 1327 comps[newcomp] = 1
1312 1328 state += 1
1313 1329 outcomps = comps.keys()
1314 1330 outcomps.sort()
1315 1331 #print "T:",text,"OC:",outcomps # dbg
1316 1332 #print "vars:",self.user_ns.keys()
1317 1333 return outcomps
1318 1334
1319 1335 def set_custom_completer(self,completer,pos=0):
1320 1336 """Adds a new custom completer function.
1321 1337
1322 1338 The position argument (defaults to 0) is the index in the completers
1323 1339 list where you want the completer to be inserted."""
1324 1340
1325 1341 newcomp = new.instancemethod(completer,self.Completer,
1326 1342 self.Completer.__class__)
1327 1343 self.Completer.matchers.insert(pos,newcomp)
1328 1344
1329 1345 def set_completer(self):
1330 1346 """Reset readline's completer to be our own."""
1331 1347 self.readline.set_completer(self.Completer.complete)
1332 1348
1333 1349 def set_completer_frame(self, frame=None):
1334 1350 """Set the frame of the completer."""
1335 1351 if frame:
1336 1352 self.Completer.namespace = frame.f_locals
1337 1353 self.Completer.global_namespace = frame.f_globals
1338 1354 else:
1339 1355 self.Completer.namespace = self.user_ns
1340 1356 self.Completer.global_namespace = self.user_global_ns
1341 1357
1342 1358 #-------------------------------------------------------------------------
1343 1359 # Things related to readline
1344 1360 #-------------------------------------------------------------------------
1345 1361
1346 1362 def init_readline(self):
1347 1363 """Command history completion/saving/reloading."""
1348 1364
1349 1365 if self.readline_use:
1350 1366 import IPython.utils.rlineimpl as readline
1351 1367
1352 1368 self.rl_next_input = None
1353 1369 self.rl_do_indent = False
1354 1370
1355 1371 if not self.readline_use or not readline.have_readline:
1356 1372 self.has_readline = False
1357 1373 self.readline = None
1358 1374 # Set a number of methods that depend on readline to be no-op
1359 1375 self.savehist = no_op
1360 1376 self.reloadhist = no_op
1361 1377 self.set_completer = no_op
1362 1378 self.set_custom_completer = no_op
1363 1379 self.set_completer_frame = no_op
1364 1380 warn('Readline services not available or not loaded.')
1365 1381 else:
1366 1382 self.has_readline = True
1367 1383 self.readline = readline
1368 1384 sys.modules['readline'] = readline
1369 1385 import atexit
1370 1386 from IPython.core.completer import IPCompleter
1371 1387 self.Completer = IPCompleter(self,
1372 1388 self.user_ns,
1373 1389 self.user_global_ns,
1374 1390 self.readline_omit__names,
1375 1391 self.alias_manager.alias_table)
1376 1392 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1377 1393 self.strdispatchers['complete_command'] = sdisp
1378 1394 self.Completer.custom_completers = sdisp
1379 1395 # Platform-specific configuration
1380 1396 if os.name == 'nt':
1381 1397 self.readline_startup_hook = readline.set_pre_input_hook
1382 1398 else:
1383 1399 self.readline_startup_hook = readline.set_startup_hook
1384 1400
1385 1401 # Load user's initrc file (readline config)
1386 1402 # Or if libedit is used, load editrc.
1387 1403 inputrc_name = os.environ.get('INPUTRC')
1388 1404 if inputrc_name is None:
1389 1405 home_dir = get_home_dir()
1390 1406 if home_dir is not None:
1391 1407 inputrc_name = '.inputrc'
1392 1408 if readline.uses_libedit:
1393 1409 inputrc_name = '.editrc'
1394 1410 inputrc_name = os.path.join(home_dir, inputrc_name)
1395 1411 if os.path.isfile(inputrc_name):
1396 1412 try:
1397 1413 readline.read_init_file(inputrc_name)
1398 1414 except:
1399 1415 warn('Problems reading readline initialization file <%s>'
1400 1416 % inputrc_name)
1401 1417
1402 1418 # save this in sys so embedded copies can restore it properly
1403 1419 sys.ipcompleter = self.Completer.complete
1404 1420 self.set_completer()
1405 1421
1406 1422 # Configure readline according to user's prefs
1407 1423 # This is only done if GNU readline is being used. If libedit
1408 1424 # is being used (as on Leopard) the readline config is
1409 1425 # not run as the syntax for libedit is different.
1410 1426 if not readline.uses_libedit:
1411 1427 for rlcommand in self.readline_parse_and_bind:
1412 1428 #print "loading rl:",rlcommand # dbg
1413 1429 readline.parse_and_bind(rlcommand)
1414 1430
1415 1431 # Remove some chars from the delimiters list. If we encounter
1416 1432 # unicode chars, discard them.
1417 1433 delims = readline.get_completer_delims().encode("ascii", "ignore")
1418 1434 delims = delims.translate(string._idmap,
1419 1435 self.readline_remove_delims)
1420 1436 readline.set_completer_delims(delims)
1421 1437 # otherwise we end up with a monster history after a while:
1422 1438 readline.set_history_length(1000)
1423 1439 try:
1424 1440 #print '*** Reading readline history' # dbg
1425 1441 readline.read_history_file(self.histfile)
1426 1442 except IOError:
1427 1443 pass # It doesn't exist yet.
1428 1444
1429 1445 atexit.register(self.atexit_operations)
1430 1446 del atexit
1431 1447
1432 1448 # Configure auto-indent for all platforms
1433 1449 self.set_autoindent(self.autoindent)
1434 1450
1435 1451 def set_next_input(self, s):
1436 1452 """ Sets the 'default' input string for the next command line.
1437 1453
1438 1454 Requires readline.
1439 1455
1440 1456 Example:
1441 1457
1442 1458 [D:\ipython]|1> _ip.set_next_input("Hello Word")
1443 1459 [D:\ipython]|2> Hello Word_ # cursor is here
1444 1460 """
1445 1461
1446 1462 self.rl_next_input = s
1447 1463
1448 1464 # Maybe move this to the terminal subclass?
1449 1465 def pre_readline(self):
1450 1466 """readline hook to be used at the start of each line.
1451 1467
1452 1468 Currently it handles auto-indent only."""
1453 1469
1454 1470 if self.rl_do_indent:
1455 1471 self.readline.insert_text(self._indent_current_str())
1456 1472 if self.rl_next_input is not None:
1457 1473 self.readline.insert_text(self.rl_next_input)
1458 1474 self.rl_next_input = None
1459 1475
1460 1476 def _indent_current_str(self):
1461 1477 """return the current level of indentation as a string"""
1462 1478 return self.indent_current_nsp * ' '
1463 1479
1464 1480 #-------------------------------------------------------------------------
1465 1481 # Things related to magics
1466 1482 #-------------------------------------------------------------------------
1467 1483
1468 1484 def init_magics(self):
1469 1485 # Set user colors (don't do it in the constructor above so that it
1470 1486 # doesn't crash if colors option is invalid)
1471 1487 self.magic_colors(self.colors)
1472 1488 # History was moved to a separate module
1473 1489 from . import history
1474 1490 history.init_ipython(self)
1475 1491
1476 1492 def magic(self,arg_s):
1477 1493 """Call a magic function by name.
1478 1494
1479 1495 Input: a string containing the name of the magic function to call and any
1480 1496 additional arguments to be passed to the magic.
1481 1497
1482 1498 magic('name -opt foo bar') is equivalent to typing at the ipython
1483 1499 prompt:
1484 1500
1485 1501 In[1]: %name -opt foo bar
1486 1502
1487 1503 To call a magic without arguments, simply use magic('name').
1488 1504
1489 1505 This provides a proper Python function to call IPython's magics in any
1490 1506 valid Python code you can type at the interpreter, including loops and
1491 1507 compound statements.
1492 1508 """
1493 1509 args = arg_s.split(' ',1)
1494 1510 magic_name = args[0]
1495 1511 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
1496 1512
1497 1513 try:
1498 1514 magic_args = args[1]
1499 1515 except IndexError:
1500 1516 magic_args = ''
1501 1517 fn = getattr(self,'magic_'+magic_name,None)
1502 1518 if fn is None:
1503 1519 error("Magic function `%s` not found." % magic_name)
1504 1520 else:
1505 1521 magic_args = self.var_expand(magic_args,1)
1506 1522 with nested(self.builtin_trap,):
1507 1523 result = fn(magic_args)
1508 1524 return result
1509 1525
1510 1526 def define_magic(self, magicname, func):
1511 1527 """Expose own function as magic function for ipython
1512 1528
1513 1529 def foo_impl(self,parameter_s=''):
1514 1530 'My very own magic!. (Use docstrings, IPython reads them).'
1515 1531 print 'Magic function. Passed parameter is between < >:'
1516 1532 print '<%s>' % parameter_s
1517 1533 print 'The self object is:',self
1518 1534
1519 1535 self.define_magic('foo',foo_impl)
1520 1536 """
1521 1537
1522 1538 import new
1523 1539 im = new.instancemethod(func,self, self.__class__)
1524 1540 old = getattr(self, "magic_" + magicname, None)
1525 1541 setattr(self, "magic_" + magicname, im)
1526 1542 return old
1527 1543
1528 1544 #-------------------------------------------------------------------------
1529 1545 # Things related to macros
1530 1546 #-------------------------------------------------------------------------
1531 1547
1532 1548 def define_macro(self, name, themacro):
1533 1549 """Define a new macro
1534 1550
1535 1551 Parameters
1536 1552 ----------
1537 1553 name : str
1538 1554 The name of the macro.
1539 1555 themacro : str or Macro
1540 1556 The action to do upon invoking the macro. If a string, a new
1541 1557 Macro object is created by passing the string to it.
1542 1558 """
1543 1559
1544 1560 from IPython.core import macro
1545 1561
1546 1562 if isinstance(themacro, basestring):
1547 1563 themacro = macro.Macro(themacro)
1548 1564 if not isinstance(themacro, macro.Macro):
1549 1565 raise ValueError('A macro must be a string or a Macro instance.')
1550 1566 self.user_ns[name] = themacro
1551 1567
1552 1568 #-------------------------------------------------------------------------
1553 1569 # Things related to the running of system commands
1554 1570 #-------------------------------------------------------------------------
1555 1571
1556 1572 def system(self, cmd):
1557 1573 """Make a system call, using IPython."""
1558 1574 return self.hooks.shell_hook(self.var_expand(cmd, depth=2))
1559 1575
1560 1576 #-------------------------------------------------------------------------
1561 1577 # Things related to aliases
1562 1578 #-------------------------------------------------------------------------
1563 1579
1564 1580 def init_alias(self):
1565 1581 self.alias_manager = AliasManager(shell=self, config=self.config)
1566 1582 self.ns_table['alias'] = self.alias_manager.alias_table,
1567 1583
1568 1584 #-------------------------------------------------------------------------
1569 1585 # Things related to extensions and plugins
1570 1586 #-------------------------------------------------------------------------
1571 1587
1572 1588 def init_extension_manager(self):
1573 1589 self.extension_manager = ExtensionManager(shell=self, config=self.config)
1574 1590
1575 1591 def init_plugin_manager(self):
1576 1592 self.plugin_manager = PluginManager(config=self.config)
1577 1593
1578 1594 #-------------------------------------------------------------------------
1579 1595 # Things related to the prefilter
1580 1596 #-------------------------------------------------------------------------
1581 1597
1582 1598 def init_prefilter(self):
1583 1599 self.prefilter_manager = PrefilterManager(shell=self, config=self.config)
1584 1600 # Ultimately this will be refactored in the new interpreter code, but
1585 1601 # for now, we should expose the main prefilter method (there's legacy
1586 1602 # code out there that may rely on this).
1587 1603 self.prefilter = self.prefilter_manager.prefilter_lines
1588 1604
1589 1605 #-------------------------------------------------------------------------
1590 1606 # Things related to the running of code
1591 1607 #-------------------------------------------------------------------------
1592 1608
1593 1609 def ex(self, cmd):
1594 1610 """Execute a normal python statement in user namespace."""
1595 1611 with nested(self.builtin_trap,):
1596 1612 exec cmd in self.user_global_ns, self.user_ns
1597 1613
1598 1614 def ev(self, expr):
1599 1615 """Evaluate python expression expr in user namespace.
1600 1616
1601 1617 Returns the result of evaluation
1602 1618 """
1603 1619 with nested(self.builtin_trap,):
1604 1620 return eval(expr, self.user_global_ns, self.user_ns)
1605 1621
1606 1622 def safe_execfile(self, fname, *where, **kw):
1607 1623 """A safe version of the builtin execfile().
1608 1624
1609 1625 This version will never throw an exception, but instead print
1610 1626 helpful error messages to the screen. This only works on pure
1611 1627 Python files with the .py extension.
1612 1628
1613 1629 Parameters
1614 1630 ----------
1615 1631 fname : string
1616 1632 The name of the file to be executed.
1617 1633 where : tuple
1618 1634 One or two namespaces, passed to execfile() as (globals,locals).
1619 1635 If only one is given, it is passed as both.
1620 1636 exit_ignore : bool (False)
1621 1637 If True, then silence SystemExit for non-zero status (it is always
1622 1638 silenced for zero status, as it is so common).
1623 1639 """
1624 1640 kw.setdefault('exit_ignore', False)
1625 1641
1626 1642 fname = os.path.abspath(os.path.expanduser(fname))
1627 1643
1628 1644 # Make sure we have a .py file
1629 1645 if not fname.endswith('.py'):
1630 1646 warn('File must end with .py to be run using execfile: <%s>' % fname)
1631 1647
1632 1648 # Make sure we can open the file
1633 1649 try:
1634 1650 with open(fname) as thefile:
1635 1651 pass
1636 1652 except:
1637 1653 warn('Could not open file <%s> for safe execution.' % fname)
1638 1654 return
1639 1655
1640 1656 # Find things also in current directory. This is needed to mimic the
1641 1657 # behavior of running a script from the system command line, where
1642 1658 # Python inserts the script's directory into sys.path
1643 1659 dname = os.path.dirname(fname)
1644 1660
1645 1661 with prepended_to_syspath(dname):
1646 1662 try:
1647 1663 execfile(fname,*where)
1648 1664 except SystemExit, status:
1649 1665 # If the call was made with 0 or None exit status (sys.exit(0)
1650 1666 # or sys.exit() ), don't bother showing a traceback, as both of
1651 1667 # these are considered normal by the OS:
1652 1668 # > python -c'import sys;sys.exit(0)'; echo $?
1653 1669 # 0
1654 1670 # > python -c'import sys;sys.exit()'; echo $?
1655 1671 # 0
1656 1672 # For other exit status, we show the exception unless
1657 1673 # explicitly silenced, but only in short form.
1658 1674 if status.code not in (0, None) and not kw['exit_ignore']:
1659 1675 self.showtraceback(exception_only=True)
1660 1676 except:
1661 1677 self.showtraceback()
1662 1678
1663 1679 def safe_execfile_ipy(self, fname):
1664 1680 """Like safe_execfile, but for .ipy files with IPython syntax.
1665 1681
1666 1682 Parameters
1667 1683 ----------
1668 1684 fname : str
1669 1685 The name of the file to execute. The filename must have a
1670 1686 .ipy extension.
1671 1687 """
1672 1688 fname = os.path.abspath(os.path.expanduser(fname))
1673 1689
1674 1690 # Make sure we have a .py file
1675 1691 if not fname.endswith('.ipy'):
1676 1692 warn('File must end with .py to be run using execfile: <%s>' % fname)
1677 1693
1678 1694 # Make sure we can open the file
1679 1695 try:
1680 1696 with open(fname) as thefile:
1681 1697 pass
1682 1698 except:
1683 1699 warn('Could not open file <%s> for safe execution.' % fname)
1684 1700 return
1685 1701
1686 1702 # Find things also in current directory. This is needed to mimic the
1687 1703 # behavior of running a script from the system command line, where
1688 1704 # Python inserts the script's directory into sys.path
1689 1705 dname = os.path.dirname(fname)
1690 1706
1691 1707 with prepended_to_syspath(dname):
1692 1708 try:
1693 1709 with open(fname) as thefile:
1694 1710 script = thefile.read()
1695 1711 # self.runlines currently captures all exceptions
1696 1712 # raise in user code. It would be nice if there were
1697 1713 # versions of runlines, execfile that did raise, so
1698 1714 # we could catch the errors.
1699 1715 self.runlines(script, clean=True)
1700 1716 except:
1701 1717 self.showtraceback()
1702 1718 warn('Unknown failure executing file: <%s>' % fname)
1703 1719
1704 1720 def runlines(self, lines, clean=False):
1705 1721 """Run a string of one or more lines of source.
1706 1722
1707 1723 This method is capable of running a string containing multiple source
1708 1724 lines, as if they had been entered at the IPython prompt. Since it
1709 1725 exposes IPython's processing machinery, the given strings can contain
1710 1726 magic calls (%magic), special shell access (!cmd), etc.
1711 1727 """
1712 1728
1713 1729 if isinstance(lines, (list, tuple)):
1714 1730 lines = '\n'.join(lines)
1715 1731
1716 1732 if clean:
1717 1733 lines = self._cleanup_ipy_script(lines)
1718 1734
1719 1735 # We must start with a clean buffer, in case this is run from an
1720 1736 # interactive IPython session (via a magic, for example).
1721 1737 self.resetbuffer()
1722 1738 lines = lines.splitlines()
1723 1739 more = 0
1724 1740
1725 1741 with nested(self.builtin_trap, self.display_trap):
1726 1742 for line in lines:
1727 1743 # skip blank lines so we don't mess up the prompt counter, but do
1728 1744 # NOT skip even a blank line if we are in a code block (more is
1729 1745 # true)
1730 1746
1731 1747 if line or more:
1732 1748 # push to raw history, so hist line numbers stay in sync
1733 1749 self.input_hist_raw.append("# " + line + "\n")
1734 1750 prefiltered = self.prefilter_manager.prefilter_lines(line,more)
1735 1751 more = self.push_line(prefiltered)
1736 1752 # IPython's runsource returns None if there was an error
1737 1753 # compiling the code. This allows us to stop processing right
1738 1754 # away, so the user gets the error message at the right place.
1739 1755 if more is None:
1740 1756 break
1741 1757 else:
1742 1758 self.input_hist_raw.append("\n")
1743 1759 # final newline in case the input didn't have it, so that the code
1744 1760 # actually does get executed
1745 1761 if more:
1746 1762 self.push_line('\n')
1747 1763
1748 1764 def runsource(self, source, filename='<input>', symbol='single'):
1749 1765 """Compile and run some source in the interpreter.
1750 1766
1751 1767 Arguments are as for compile_command().
1752 1768
1753 1769 One several things can happen:
1754 1770
1755 1771 1) The input is incorrect; compile_command() raised an
1756 1772 exception (SyntaxError or OverflowError). A syntax traceback
1757 1773 will be printed by calling the showsyntaxerror() method.
1758 1774
1759 1775 2) The input is incomplete, and more input is required;
1760 1776 compile_command() returned None. Nothing happens.
1761 1777
1762 1778 3) The input is complete; compile_command() returned a code
1763 1779 object. The code is executed by calling self.runcode() (which
1764 1780 also handles run-time exceptions, except for SystemExit).
1765 1781
1766 1782 The return value is:
1767 1783
1768 1784 - True in case 2
1769 1785
1770 1786 - False in the other cases, unless an exception is raised, where
1771 1787 None is returned instead. This can be used by external callers to
1772 1788 know whether to continue feeding input or not.
1773 1789
1774 1790 The return value can be used to decide whether to use sys.ps1 or
1775 1791 sys.ps2 to prompt the next line."""
1776 1792
1777 1793 # if the source code has leading blanks, add 'if 1:\n' to it
1778 1794 # this allows execution of indented pasted code. It is tempting
1779 1795 # to add '\n' at the end of source to run commands like ' a=1'
1780 1796 # directly, but this fails for more complicated scenarios
1781 1797 source=source.encode(self.stdin_encoding)
1782 1798 if source[:1] in [' ', '\t']:
1783 1799 source = 'if 1:\n%s' % source
1784 1800
1785 1801 try:
1786 1802 code = self.compile(source,filename,symbol)
1787 1803 except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError):
1788 1804 # Case 1
1789 1805 self.showsyntaxerror(filename)
1790 1806 return None
1791 1807
1792 1808 if code is None:
1793 1809 # Case 2
1794 1810 return True
1795 1811
1796 1812 # Case 3
1797 1813 # We store the code object so that threaded shells and
1798 1814 # custom exception handlers can access all this info if needed.
1799 1815 # The source corresponding to this can be obtained from the
1800 1816 # buffer attribute as '\n'.join(self.buffer).
1801 1817 self.code_to_run = code
1802 1818 # now actually execute the code object
1803 1819 if self.runcode(code) == 0:
1804 1820 return False
1805 1821 else:
1806 1822 return None
1807 1823
1808 1824 def runcode(self,code_obj):
1809 1825 """Execute a code object.
1810 1826
1811 1827 When an exception occurs, self.showtraceback() is called to display a
1812 1828 traceback.
1813 1829
1814 1830 Return value: a flag indicating whether the code to be run completed
1815 1831 successfully:
1816 1832
1817 1833 - 0: successful execution.
1818 1834 - 1: an error occurred.
1819 1835 """
1820 1836
1821 1837 # Set our own excepthook in case the user code tries to call it
1822 1838 # directly, so that the IPython crash handler doesn't get triggered
1823 1839 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
1824 1840
1825 1841 # we save the original sys.excepthook in the instance, in case config
1826 1842 # code (such as magics) needs access to it.
1827 1843 self.sys_excepthook = old_excepthook
1828 1844 outflag = 1 # happens in more places, so it's easier as default
1829 1845 try:
1830 1846 try:
1831 1847 self.hooks.pre_runcode_hook()
1832 1848 exec code_obj in self.user_global_ns, self.user_ns
1833 1849 finally:
1834 1850 # Reset our crash handler in place
1835 1851 sys.excepthook = old_excepthook
1836 1852 except SystemExit:
1837 1853 self.resetbuffer()
1838 1854 self.showtraceback(exception_only=True)
1839 1855 warn("To exit: use any of 'exit', 'quit', %Exit or Ctrl-D.", level=1)
1840 1856 except self.custom_exceptions:
1841 1857 etype,value,tb = sys.exc_info()
1842 1858 self.CustomTB(etype,value,tb)
1843 1859 except:
1844 1860 self.showtraceback()
1845 1861 else:
1846 1862 outflag = 0
1847 1863 if softspace(sys.stdout, 0):
1848 1864 print
1849 1865 # Flush out code object which has been run (and source)
1850 1866 self.code_to_run = None
1851 1867 return outflag
1852 1868
1853 1869 def push_line(self, line):
1854 1870 """Push a line to the interpreter.
1855 1871
1856 1872 The line should not have a trailing newline; it may have
1857 1873 internal newlines. The line is appended to a buffer and the
1858 1874 interpreter's runsource() method is called with the
1859 1875 concatenated contents of the buffer as source. If this
1860 1876 indicates that the command was executed or invalid, the buffer
1861 1877 is reset; otherwise, the command is incomplete, and the buffer
1862 1878 is left as it was after the line was appended. The return
1863 1879 value is 1 if more input is required, 0 if the line was dealt
1864 1880 with in some way (this is the same as runsource()).
1865 1881 """
1866 1882
1867 1883 # autoindent management should be done here, and not in the
1868 1884 # interactive loop, since that one is only seen by keyboard input. We
1869 1885 # need this done correctly even for code run via runlines (which uses
1870 1886 # push).
1871 1887
1872 1888 #print 'push line: <%s>' % line # dbg
1873 1889 for subline in line.splitlines():
1874 1890 self._autoindent_update(subline)
1875 1891 self.buffer.append(line)
1876 1892 more = self.runsource('\n'.join(self.buffer), self.filename)
1877 1893 if not more:
1878 1894 self.resetbuffer()
1879 1895 return more
1880 1896
1881 1897 def resetbuffer(self):
1882 1898 """Reset the input buffer."""
1883 1899 self.buffer[:] = []
1884 1900
1885 1901 def _is_secondary_block_start(self, s):
1886 1902 if not s.endswith(':'):
1887 1903 return False
1888 1904 if (s.startswith('elif') or
1889 1905 s.startswith('else') or
1890 1906 s.startswith('except') or
1891 1907 s.startswith('finally')):
1892 1908 return True
1893 1909
1894 1910 def _cleanup_ipy_script(self, script):
1895 1911 """Make a script safe for self.runlines()
1896 1912
1897 1913 Currently, IPython is lines based, with blocks being detected by
1898 1914 empty lines. This is a problem for block based scripts that may
1899 1915 not have empty lines after blocks. This script adds those empty
1900 1916 lines to make scripts safe for running in the current line based
1901 1917 IPython.
1902 1918 """
1903 1919 res = []
1904 1920 lines = script.splitlines()
1905 1921 level = 0
1906 1922
1907 1923 for l in lines:
1908 1924 lstripped = l.lstrip()
1909 1925 stripped = l.strip()
1910 1926 if not stripped:
1911 1927 continue
1912 1928 newlevel = len(l) - len(lstripped)
1913 1929 if level > 0 and newlevel == 0 and \
1914 1930 not self._is_secondary_block_start(stripped):
1915 1931 # add empty line
1916 1932 res.append('')
1917 1933 res.append(l)
1918 1934 level = newlevel
1919 1935
1920 1936 return '\n'.join(res) + '\n'
1921 1937
1922 1938 def _autoindent_update(self,line):
1923 1939 """Keep track of the indent level."""
1924 1940
1925 1941 #debugx('line')
1926 1942 #debugx('self.indent_current_nsp')
1927 1943 if self.autoindent:
1928 1944 if line:
1929 1945 inisp = num_ini_spaces(line)
1930 1946 if inisp < self.indent_current_nsp:
1931 1947 self.indent_current_nsp = inisp
1932 1948
1933 1949 if line[-1] == ':':
1934 1950 self.indent_current_nsp += 4
1935 1951 elif dedent_re.match(line):
1936 1952 self.indent_current_nsp -= 4
1937 1953 else:
1938 1954 self.indent_current_nsp = 0
1939 1955
1940 1956 #-------------------------------------------------------------------------
1941 1957 # Things related to GUI support and pylab
1942 1958 #-------------------------------------------------------------------------
1943 1959
1944 1960 def enable_pylab(self, gui=None):
1945 1961 raise NotImplementedError('Implement enable_pylab in a subclass')
1946 1962
1947 1963 #-------------------------------------------------------------------------
1948 1964 # Utilities
1949 1965 #-------------------------------------------------------------------------
1950 1966
1951 1967 def getoutput(self, cmd):
1952 1968 return getoutput(self.var_expand(cmd,depth=2),
1953 1969 header=self.system_header,
1954 1970 verbose=self.system_verbose)
1955 1971
1956 1972 def getoutputerror(self, cmd):
1957 1973 return getoutputerror(self.var_expand(cmd,depth=2),
1958 1974 header=self.system_header,
1959 1975 verbose=self.system_verbose)
1960 1976
1961 1977 def var_expand(self,cmd,depth=0):
1962 1978 """Expand python variables in a string.
1963 1979
1964 1980 The depth argument indicates how many frames above the caller should
1965 1981 be walked to look for the local namespace where to expand variables.
1966 1982
1967 1983 The global namespace for expansion is always the user's interactive
1968 1984 namespace.
1969 1985 """
1970 1986
1971 1987 return str(ItplNS(cmd,
1972 1988 self.user_ns, # globals
1973 1989 # Skip our own frame in searching for locals:
1974 1990 sys._getframe(depth+1).f_locals # locals
1975 1991 ))
1976 1992
1977 1993 def mktempfile(self,data=None):
1978 1994 """Make a new tempfile and return its filename.
1979 1995
1980 1996 This makes a call to tempfile.mktemp, but it registers the created
1981 1997 filename internally so ipython cleans it up at exit time.
1982 1998
1983 1999 Optional inputs:
1984 2000
1985 2001 - data(None): if data is given, it gets written out to the temp file
1986 2002 immediately, and the file is closed again."""
1987 2003
1988 2004 filename = tempfile.mktemp('.py','ipython_edit_')
1989 2005 self.tempfiles.append(filename)
1990 2006
1991 2007 if data:
1992 2008 tmp_file = open(filename,'w')
1993 2009 tmp_file.write(data)
1994 2010 tmp_file.close()
1995 2011 return filename
1996 2012
1997 2013 # TODO: This should be removed when Term is refactored.
1998 2014 def write(self,data):
1999 2015 """Write a string to the default output"""
2000 Term.cout.write(data)
2016 IPython.utils.io.Term.cout.write(data)
2001 2017
2002 2018 # TODO: This should be removed when Term is refactored.
2003 2019 def write_err(self,data):
2004 2020 """Write a string to the default error output"""
2005 Term.cerr.write(data)
2021 IPython.utils.io.Term.cerr.write(data)
2006 2022
2007 2023 def ask_yes_no(self,prompt,default=True):
2008 2024 if self.quiet:
2009 2025 return True
2010 2026 return ask_yes_no(prompt,default)
2011 2027
2012 2028 #-------------------------------------------------------------------------
2013 2029 # Things related to IPython exiting
2014 2030 #-------------------------------------------------------------------------
2015 2031
2016 2032 def atexit_operations(self):
2017 2033 """This will be executed at the time of exit.
2018 2034
2019 2035 Saving of persistent data should be performed here.
2020 2036 """
2021 2037 self.savehist()
2022 2038
2023 2039 # Cleanup all tempfiles left around
2024 2040 for tfile in self.tempfiles:
2025 2041 try:
2026 2042 os.unlink(tfile)
2027 2043 except OSError:
2028 2044 pass
2029 2045
2030 2046 # Clear all user namespaces to release all references cleanly.
2031 2047 self.reset()
2032 2048
2033 2049 # Run user hooks
2034 2050 self.hooks.shutdown_hook()
2035 2051
2036 2052 def cleanup(self):
2037 2053 self.restore_sys_module_state()
2038 2054
2039 2055
2040 2056 class InteractiveShellABC(object):
2041 2057 """An abstract base class for InteractiveShell."""
2042 2058 __metaclass__ = abc.ABCMeta
2043 2059
2044 2060 InteractiveShellABC.register(InteractiveShell)
@@ -1,41 +1,41 b''
1 1 """Support for interactive macros in IPython"""
2 2
3 3 #*****************************************************************************
4 4 # Copyright (C) 2001-2005 Fernando Perez <fperez@colorado.edu>
5 5 #
6 6 # Distributed under the terms of the BSD License. The full license is in
7 7 # the file COPYING, distributed as part of this software.
8 8 #*****************************************************************************
9 9
10 from IPython.utils.io import Term
10 import IPython.utils.io
11 11 from IPython.core.autocall import IPyAutocall
12 12
13 13 class Macro(IPyAutocall):
14 14 """Simple class to store the value of macros as strings.
15 15
16 16 Macro is just a callable that executes a string of IPython
17 17 input when called.
18 18
19 19 Args to macro are available in _margv list if you need them.
20 20 """
21 21
22 22 def __init__(self,data):
23 23
24 24 # store the macro value, as a single string which can be evaluated by
25 25 # runlines()
26 26 self.value = ''.join(data).rstrip()+'\n'
27 27
28 28 def __str__(self):
29 29 return self.value
30 30
31 31 def __repr__(self):
32 32 return 'IPython.macro.Macro(%s)' % repr(self.value)
33 33
34 34 def __call__(self,*args):
35 Term.cout.flush()
35 IPython.utils.io.Term.cout.flush()
36 36 self._ip.user_ns['_margv'] = args
37 37 self._ip.runlines(self.value)
38 38
39 39 def __getstate__(self):
40 40 """ needed for safe pickling via %store """
41 41 return {'value': self.value}
@@ -1,3651 +1,3652 b''
1 1 # encoding: utf-8
2 2 """Magic functions for InteractiveShell.
3 3 """
4 4
5 5 #-----------------------------------------------------------------------------
6 6 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
7 7 # Copyright (C) 2001-2007 Fernando Perez <fperez@colorado.edu>
8 8 # Copyright (C) 2008-2009 The IPython Development Team
9 9
10 10 # Distributed under the terms of the BSD License. The full license is in
11 11 # the file COPYING, distributed as part of this software.
12 12 #-----------------------------------------------------------------------------
13 13
14 14 #-----------------------------------------------------------------------------
15 15 # Imports
16 16 #-----------------------------------------------------------------------------
17 17
18 18 import __builtin__
19 19 import __future__
20 20 import bdb
21 21 import inspect
22 22 import os
23 23 import sys
24 24 import shutil
25 25 import re
26 26 import time
27 27 import textwrap
28 28 import types
29 29 from cStringIO import StringIO
30 30 from getopt import getopt,GetoptError
31 31 from pprint import pformat
32 32
33 33 # cProfile was added in Python2.5
34 34 try:
35 35 import cProfile as profile
36 36 import pstats
37 37 except ImportError:
38 38 # profile isn't bundled by default in Debian for license reasons
39 39 try:
40 40 import profile,pstats
41 41 except ImportError:
42 42 profile = pstats = None
43 43
44 44 # print_function was added to __future__ in Python2.6, remove this when we drop
45 45 # 2.5 compatibility
46 46 if not hasattr(__future__,'CO_FUTURE_PRINT_FUNCTION'):
47 47 __future__.CO_FUTURE_PRINT_FUNCTION = 65536
48 48
49 49 import IPython
50 50 from IPython.core import debugger, oinspect
51 51 from IPython.core.error import TryNext
52 52 from IPython.core.error import UsageError
53 53 from IPython.core.fakemodule import FakeModule
54 54 from IPython.core.macro import Macro
55 55 from IPython.core.page import page
56 56 from IPython.core.prefilter import ESC_MAGIC
57 57 from IPython.lib.pylabtools import mpl_runner
58 58 from IPython.lib.inputhook import enable_gui
59 59 from IPython.external.Itpl import itpl, printpl
60 60 from IPython.testing import decorators as testdec
61 from IPython.utils.io import Term, file_read, nlprint
61 from IPython.utils.io import file_read, nlprint
62 import IPython.utils.io
62 63 from IPython.utils.path import get_py_filename
63 64 from IPython.utils.process import arg_split, abbrev_cwd
64 65 from IPython.utils.terminal import set_term_title
65 66 from IPython.utils.text import LSString, SList, StringTypes
66 67 from IPython.utils.timing import clock, clock2
67 68 from IPython.utils.warn import warn, error
68 69 from IPython.utils.ipstruct import Struct
69 70 import IPython.utils.generics
70 71
71 72 #-----------------------------------------------------------------------------
72 73 # Utility functions
73 74 #-----------------------------------------------------------------------------
74 75
75 76 def on_off(tag):
76 77 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
77 78 return ['OFF','ON'][tag]
78 79
79 80 class Bunch: pass
80 81
81 82 def compress_dhist(dh):
82 83 head, tail = dh[:-10], dh[-10:]
83 84
84 85 newhead = []
85 86 done = set()
86 87 for h in head:
87 88 if h in done:
88 89 continue
89 90 newhead.append(h)
90 91 done.add(h)
91 92
92 93 return newhead + tail
93 94
94 95
95 96 #***************************************************************************
96 97 # Main class implementing Magic functionality
97 98
98 99 # XXX - for some odd reason, if Magic is made a new-style class, we get errors
99 100 # on construction of the main InteractiveShell object. Something odd is going
100 101 # on with super() calls, Configurable and the MRO... For now leave it as-is, but
101 102 # eventually this needs to be clarified.
102 103 # BG: This is because InteractiveShell inherits from this, but is itself a
103 104 # Configurable. This messes up the MRO in some way. The fix is that we need to
104 105 # make Magic a configurable that InteractiveShell does not subclass.
105 106
106 107 class Magic:
107 108 """Magic functions for InteractiveShell.
108 109
109 110 Shell functions which can be reached as %function_name. All magic
110 111 functions should accept a string, which they can parse for their own
111 112 needs. This can make some functions easier to type, eg `%cd ../`
112 113 vs. `%cd("../")`
113 114
114 115 ALL definitions MUST begin with the prefix magic_. The user won't need it
115 116 at the command line, but it is is needed in the definition. """
116 117
117 118 # class globals
118 119 auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.',
119 120 'Automagic is ON, % prefix NOT needed for magic functions.']
120 121
121 122 #......................................................................
122 123 # some utility functions
123 124
124 125 def __init__(self,shell):
125 126
126 127 self.options_table = {}
127 128 if profile is None:
128 129 self.magic_prun = self.profile_missing_notice
129 130 self.shell = shell
130 131
131 132 # namespace for holding state we may need
132 133 self._magic_state = Bunch()
133 134
134 135 def profile_missing_notice(self, *args, **kwargs):
135 136 error("""\
136 137 The profile module could not be found. It has been removed from the standard
137 138 python packages because of its non-free license. To use profiling, install the
138 139 python-profiler package from non-free.""")
139 140
140 141 def default_option(self,fn,optstr):
141 142 """Make an entry in the options_table for fn, with value optstr"""
142 143
143 144 if fn not in self.lsmagic():
144 145 error("%s is not a magic function" % fn)
145 146 self.options_table[fn] = optstr
146 147
147 148 def lsmagic(self):
148 149 """Return a list of currently available magic functions.
149 150
150 151 Gives a list of the bare names after mangling (['ls','cd', ...], not
151 152 ['magic_ls','magic_cd',...]"""
152 153
153 154 # FIXME. This needs a cleanup, in the way the magics list is built.
154 155
155 156 # magics in class definition
156 157 class_magic = lambda fn: fn.startswith('magic_') and \
157 158 callable(Magic.__dict__[fn])
158 159 # in instance namespace (run-time user additions)
159 160 inst_magic = lambda fn: fn.startswith('magic_') and \
160 161 callable(self.__dict__[fn])
161 162 # and bound magics by user (so they can access self):
162 163 inst_bound_magic = lambda fn: fn.startswith('magic_') and \
163 164 callable(self.__class__.__dict__[fn])
164 165 magics = filter(class_magic,Magic.__dict__.keys()) + \
165 166 filter(inst_magic,self.__dict__.keys()) + \
166 167 filter(inst_bound_magic,self.__class__.__dict__.keys())
167 168 out = []
168 169 for fn in set(magics):
169 170 out.append(fn.replace('magic_','',1))
170 171 out.sort()
171 172 return out
172 173
173 174 def extract_input_slices(self,slices,raw=False):
174 175 """Return as a string a set of input history slices.
175 176
176 177 Inputs:
177 178
178 179 - slices: the set of slices is given as a list of strings (like
179 180 ['1','4:8','9'], since this function is for use by magic functions
180 181 which get their arguments as strings.
181 182
182 183 Optional inputs:
183 184
184 185 - raw(False): by default, the processed input is used. If this is
185 186 true, the raw input history is used instead.
186 187
187 188 Note that slices can be called with two notations:
188 189
189 190 N:M -> standard python form, means including items N...(M-1).
190 191
191 192 N-M -> include items N..M (closed endpoint)."""
192 193
193 194 if raw:
194 195 hist = self.shell.input_hist_raw
195 196 else:
196 197 hist = self.shell.input_hist
197 198
198 199 cmds = []
199 200 for chunk in slices:
200 201 if ':' in chunk:
201 202 ini,fin = map(int,chunk.split(':'))
202 203 elif '-' in chunk:
203 204 ini,fin = map(int,chunk.split('-'))
204 205 fin += 1
205 206 else:
206 207 ini = int(chunk)
207 208 fin = ini+1
208 209 cmds.append(hist[ini:fin])
209 210 return cmds
210 211
211 212 def _ofind(self, oname, namespaces=None):
212 213 """Find an object in the available namespaces.
213 214
214 215 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
215 216
216 217 Has special code to detect magic functions.
217 218 """
218 219 oname = oname.strip()
219 220 alias_ns = None
220 221 if namespaces is None:
221 222 # Namespaces to search in:
222 223 # Put them in a list. The order is important so that we
223 224 # find things in the same order that Python finds them.
224 225 namespaces = [ ('Interactive', self.shell.user_ns),
225 226 ('IPython internal', self.shell.internal_ns),
226 227 ('Python builtin', __builtin__.__dict__),
227 228 ('Alias', self.shell.alias_manager.alias_table),
228 229 ]
229 230 alias_ns = self.shell.alias_manager.alias_table
230 231
231 232 # initialize results to 'null'
232 233 found = False; obj = None; ospace = None; ds = None;
233 234 ismagic = False; isalias = False; parent = None
234 235
235 236 # We need to special-case 'print', which as of python2.6 registers as a
236 237 # function but should only be treated as one if print_function was
237 238 # loaded with a future import. In this case, just bail.
238 239 if (oname == 'print' and not (self.shell.compile.compiler.flags &
239 240 __future__.CO_FUTURE_PRINT_FUNCTION)):
240 241 return {'found':found, 'obj':obj, 'namespace':ospace,
241 242 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
242 243
243 244 # Look for the given name by splitting it in parts. If the head is
244 245 # found, then we look for all the remaining parts as members, and only
245 246 # declare success if we can find them all.
246 247 oname_parts = oname.split('.')
247 248 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
248 249 for nsname,ns in namespaces:
249 250 try:
250 251 obj = ns[oname_head]
251 252 except KeyError:
252 253 continue
253 254 else:
254 255 #print 'oname_rest:', oname_rest # dbg
255 256 for part in oname_rest:
256 257 try:
257 258 parent = obj
258 259 obj = getattr(obj,part)
259 260 except:
260 261 # Blanket except b/c some badly implemented objects
261 262 # allow __getattr__ to raise exceptions other than
262 263 # AttributeError, which then crashes IPython.
263 264 break
264 265 else:
265 266 # If we finish the for loop (no break), we got all members
266 267 found = True
267 268 ospace = nsname
268 269 if ns == alias_ns:
269 270 isalias = True
270 271 break # namespace loop
271 272
272 273 # Try to see if it's magic
273 274 if not found:
274 275 if oname.startswith(ESC_MAGIC):
275 276 oname = oname[1:]
276 277 obj = getattr(self,'magic_'+oname,None)
277 278 if obj is not None:
278 279 found = True
279 280 ospace = 'IPython internal'
280 281 ismagic = True
281 282
282 283 # Last try: special-case some literals like '', [], {}, etc:
283 284 if not found and oname_head in ["''",'""','[]','{}','()']:
284 285 obj = eval(oname_head)
285 286 found = True
286 287 ospace = 'Interactive'
287 288
288 289 return {'found':found, 'obj':obj, 'namespace':ospace,
289 290 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
290 291
291 292 def arg_err(self,func):
292 293 """Print docstring if incorrect arguments were passed"""
293 294 print 'Error in arguments:'
294 295 print oinspect.getdoc(func)
295 296
296 297 def format_latex(self,strng):
297 298 """Format a string for latex inclusion."""
298 299
299 300 # Characters that need to be escaped for latex:
300 301 escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE)
301 302 # Magic command names as headers:
302 303 cmd_name_re = re.compile(r'^(%s.*?):' % ESC_MAGIC,
303 304 re.MULTILINE)
304 305 # Magic commands
305 306 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % ESC_MAGIC,
306 307 re.MULTILINE)
307 308 # Paragraph continue
308 309 par_re = re.compile(r'\\$',re.MULTILINE)
309 310
310 311 # The "\n" symbol
311 312 newline_re = re.compile(r'\\n')
312 313
313 314 # Now build the string for output:
314 315 #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
315 316 strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
316 317 strng)
317 318 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
318 319 strng = par_re.sub(r'\\\\',strng)
319 320 strng = escape_re.sub(r'\\\1',strng)
320 321 strng = newline_re.sub(r'\\textbackslash{}n',strng)
321 322 return strng
322 323
323 324 def format_screen(self,strng):
324 325 """Format a string for screen printing.
325 326
326 327 This removes some latex-type format codes."""
327 328 # Paragraph continue
328 329 par_re = re.compile(r'\\$',re.MULTILINE)
329 330 strng = par_re.sub('',strng)
330 331 return strng
331 332
332 333 def parse_options(self,arg_str,opt_str,*long_opts,**kw):
333 334 """Parse options passed to an argument string.
334 335
335 336 The interface is similar to that of getopt(), but it returns back a
336 337 Struct with the options as keys and the stripped argument string still
337 338 as a string.
338 339
339 340 arg_str is quoted as a true sys.argv vector by using shlex.split.
340 341 This allows us to easily expand variables, glob files, quote
341 342 arguments, etc.
342 343
343 344 Options:
344 345 -mode: default 'string'. If given as 'list', the argument string is
345 346 returned as a list (split on whitespace) instead of a string.
346 347
347 348 -list_all: put all option values in lists. Normally only options
348 349 appearing more than once are put in a list.
349 350
350 351 -posix (True): whether to split the input line in POSIX mode or not,
351 352 as per the conventions outlined in the shlex module from the
352 353 standard library."""
353 354
354 355 # inject default options at the beginning of the input line
355 356 caller = sys._getframe(1).f_code.co_name.replace('magic_','')
356 357 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
357 358
358 359 mode = kw.get('mode','string')
359 360 if mode not in ['string','list']:
360 361 raise ValueError,'incorrect mode given: %s' % mode
361 362 # Get options
362 363 list_all = kw.get('list_all',0)
363 364 posix = kw.get('posix', os.name == 'posix')
364 365
365 366 # Check if we have more than one argument to warrant extra processing:
366 367 odict = {} # Dictionary with options
367 368 args = arg_str.split()
368 369 if len(args) >= 1:
369 370 # If the list of inputs only has 0 or 1 thing in it, there's no
370 371 # need to look for options
371 372 argv = arg_split(arg_str,posix)
372 373 # Do regular option processing
373 374 try:
374 375 opts,args = getopt(argv,opt_str,*long_opts)
375 376 except GetoptError,e:
376 377 raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str,
377 378 " ".join(long_opts)))
378 379 for o,a in opts:
379 380 if o.startswith('--'):
380 381 o = o[2:]
381 382 else:
382 383 o = o[1:]
383 384 try:
384 385 odict[o].append(a)
385 386 except AttributeError:
386 387 odict[o] = [odict[o],a]
387 388 except KeyError:
388 389 if list_all:
389 390 odict[o] = [a]
390 391 else:
391 392 odict[o] = a
392 393
393 394 # Prepare opts,args for return
394 395 opts = Struct(odict)
395 396 if mode == 'string':
396 397 args = ' '.join(args)
397 398
398 399 return opts,args
399 400
400 401 #......................................................................
401 402 # And now the actual magic functions
402 403
403 404 # Functions for IPython shell work (vars,funcs, config, etc)
404 405 def magic_lsmagic(self, parameter_s = ''):
405 406 """List currently available magic functions."""
406 407 mesc = ESC_MAGIC
407 408 print 'Available magic functions:\n'+mesc+\
408 409 (' '+mesc).join(self.lsmagic())
409 410 print '\n' + Magic.auto_status[self.shell.automagic]
410 411 return None
411 412
412 413 def magic_magic(self, parameter_s = ''):
413 414 """Print information about the magic function system.
414 415
415 416 Supported formats: -latex, -brief, -rest
416 417 """
417 418
418 419 mode = ''
419 420 try:
420 421 if parameter_s.split()[0] == '-latex':
421 422 mode = 'latex'
422 423 if parameter_s.split()[0] == '-brief':
423 424 mode = 'brief'
424 425 if parameter_s.split()[0] == '-rest':
425 426 mode = 'rest'
426 427 rest_docs = []
427 428 except:
428 429 pass
429 430
430 431 magic_docs = []
431 432 for fname in self.lsmagic():
432 433 mname = 'magic_' + fname
433 434 for space in (Magic,self,self.__class__):
434 435 try:
435 436 fn = space.__dict__[mname]
436 437 except KeyError:
437 438 pass
438 439 else:
439 440 break
440 441 if mode == 'brief':
441 442 # only first line
442 443 if fn.__doc__:
443 444 fndoc = fn.__doc__.split('\n',1)[0]
444 445 else:
445 446 fndoc = 'No documentation'
446 447 else:
447 448 if fn.__doc__:
448 449 fndoc = fn.__doc__.rstrip()
449 450 else:
450 451 fndoc = 'No documentation'
451 452
452 453
453 454 if mode == 'rest':
454 455 rest_docs.append('**%s%s**::\n\n\t%s\n\n' %(ESC_MAGIC,
455 456 fname,fndoc))
456 457
457 458 else:
458 459 magic_docs.append('%s%s:\n\t%s\n' %(ESC_MAGIC,
459 460 fname,fndoc))
460 461
461 462 magic_docs = ''.join(magic_docs)
462 463
463 464 if mode == 'rest':
464 465 return "".join(rest_docs)
465 466
466 467 if mode == 'latex':
467 468 print self.format_latex(magic_docs)
468 469 return
469 470 else:
470 471 magic_docs = self.format_screen(magic_docs)
471 472 if mode == 'brief':
472 473 return magic_docs
473 474
474 475 outmsg = """
475 476 IPython's 'magic' functions
476 477 ===========================
477 478
478 479 The magic function system provides a series of functions which allow you to
479 480 control the behavior of IPython itself, plus a lot of system-type
480 481 features. All these functions are prefixed with a % character, but parameters
481 482 are given without parentheses or quotes.
482 483
483 484 NOTE: If you have 'automagic' enabled (via the command line option or with the
484 485 %automagic function), you don't need to type in the % explicitly. By default,
485 486 IPython ships with automagic on, so you should only rarely need the % escape.
486 487
487 488 Example: typing '%cd mydir' (without the quotes) changes you working directory
488 489 to 'mydir', if it exists.
489 490
490 491 You can define your own magic functions to extend the system. See the supplied
491 492 ipythonrc and example-magic.py files for details (in your ipython
492 493 configuration directory, typically $HOME/.ipython/).
493 494
494 495 You can also define your own aliased names for magic functions. In your
495 496 ipythonrc file, placing a line like:
496 497
497 498 execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
498 499
499 500 will define %pf as a new name for %profile.
500 501
501 502 You can also call magics in code using the magic() function, which IPython
502 503 automatically adds to the builtin namespace. Type 'magic?' for details.
503 504
504 505 For a list of the available magic functions, use %lsmagic. For a description
505 506 of any of them, type %magic_name?, e.g. '%cd?'.
506 507
507 508 Currently the magic system has the following functions:\n"""
508 509
509 510 mesc = ESC_MAGIC
510 511 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
511 512 "\n\n%s%s\n\n%s" % (outmsg,
512 513 magic_docs,mesc,mesc,
513 514 (' '+mesc).join(self.lsmagic()),
514 515 Magic.auto_status[self.shell.automagic] ) )
515 516
516 517 page(outmsg,screen_lines=self.shell.usable_screen_length)
517 518
518 519
519 520 def magic_autoindent(self, parameter_s = ''):
520 521 """Toggle autoindent on/off (if available)."""
521 522
522 523 self.shell.set_autoindent()
523 524 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
524 525
525 526
526 527 def magic_automagic(self, parameter_s = ''):
527 528 """Make magic functions callable without having to type the initial %.
528 529
529 530 Without argumentsl toggles on/off (when off, you must call it as
530 531 %automagic, of course). With arguments it sets the value, and you can
531 532 use any of (case insensitive):
532 533
533 534 - on,1,True: to activate
534 535
535 536 - off,0,False: to deactivate.
536 537
537 538 Note that magic functions have lowest priority, so if there's a
538 539 variable whose name collides with that of a magic fn, automagic won't
539 540 work for that function (you get the variable instead). However, if you
540 541 delete the variable (del var), the previously shadowed magic function
541 542 becomes visible to automagic again."""
542 543
543 544 arg = parameter_s.lower()
544 545 if parameter_s in ('on','1','true'):
545 546 self.shell.automagic = True
546 547 elif parameter_s in ('off','0','false'):
547 548 self.shell.automagic = False
548 549 else:
549 550 self.shell.automagic = not self.shell.automagic
550 551 print '\n' + Magic.auto_status[self.shell.automagic]
551 552
552 553 @testdec.skip_doctest
553 554 def magic_autocall(self, parameter_s = ''):
554 555 """Make functions callable without having to type parentheses.
555 556
556 557 Usage:
557 558
558 559 %autocall [mode]
559 560
560 561 The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the
561 562 value is toggled on and off (remembering the previous state).
562 563
563 564 In more detail, these values mean:
564 565
565 566 0 -> fully disabled
566 567
567 568 1 -> active, but do not apply if there are no arguments on the line.
568 569
569 570 In this mode, you get:
570 571
571 572 In [1]: callable
572 573 Out[1]: <built-in function callable>
573 574
574 575 In [2]: callable 'hello'
575 576 ------> callable('hello')
576 577 Out[2]: False
577 578
578 579 2 -> Active always. Even if no arguments are present, the callable
579 580 object is called:
580 581
581 582 In [2]: float
582 583 ------> float()
583 584 Out[2]: 0.0
584 585
585 586 Note that even with autocall off, you can still use '/' at the start of
586 587 a line to treat the first argument on the command line as a function
587 588 and add parentheses to it:
588 589
589 590 In [8]: /str 43
590 591 ------> str(43)
591 592 Out[8]: '43'
592 593
593 594 # all-random (note for auto-testing)
594 595 """
595 596
596 597 if parameter_s:
597 598 arg = int(parameter_s)
598 599 else:
599 600 arg = 'toggle'
600 601
601 602 if not arg in (0,1,2,'toggle'):
602 603 error('Valid modes: (0->Off, 1->Smart, 2->Full')
603 604 return
604 605
605 606 if arg in (0,1,2):
606 607 self.shell.autocall = arg
607 608 else: # toggle
608 609 if self.shell.autocall:
609 610 self._magic_state.autocall_save = self.shell.autocall
610 611 self.shell.autocall = 0
611 612 else:
612 613 try:
613 614 self.shell.autocall = self._magic_state.autocall_save
614 615 except AttributeError:
615 616 self.shell.autocall = self._magic_state.autocall_save = 1
616 617
617 618 print "Automatic calling is:",['OFF','Smart','Full'][self.shell.autocall]
618 619
619 620 def magic_system_verbose(self, parameter_s = ''):
620 621 """Set verbose printing of system calls.
621 622
622 623 If called without an argument, act as a toggle"""
623 624
624 625 if parameter_s:
625 626 val = bool(eval(parameter_s))
626 627 else:
627 628 val = None
628 629
629 630 if self.shell.system_verbose:
630 631 self.shell.system_verbose = False
631 632 else:
632 633 self.shell.system_verbose = True
633 634 print "System verbose printing is:",\
634 635 ['OFF','ON'][self.shell.system_verbose]
635 636
636 637
637 638 def magic_page(self, parameter_s=''):
638 639 """Pretty print the object and display it through a pager.
639 640
640 641 %page [options] OBJECT
641 642
642 643 If no object is given, use _ (last output).
643 644
644 645 Options:
645 646
646 647 -r: page str(object), don't pretty-print it."""
647 648
648 649 # After a function contributed by Olivier Aubert, slightly modified.
649 650
650 651 # Process options/args
651 652 opts,args = self.parse_options(parameter_s,'r')
652 653 raw = 'r' in opts
653 654
654 655 oname = args and args or '_'
655 656 info = self._ofind(oname)
656 657 if info['found']:
657 658 txt = (raw and str or pformat)( info['obj'] )
658 659 page(txt)
659 660 else:
660 661 print 'Object `%s` not found' % oname
661 662
662 663 def magic_profile(self, parameter_s=''):
663 664 """Print your currently active IPython profile."""
664 665 if self.shell.profile:
665 666 printpl('Current IPython profile: $self.shell.profile.')
666 667 else:
667 668 print 'No profile active.'
668 669
669 670 def magic_pinfo(self, parameter_s='', namespaces=None):
670 671 """Provide detailed information about an object.
671 672
672 673 '%pinfo object' is just a synonym for object? or ?object."""
673 674
674 675 #print 'pinfo par: <%s>' % parameter_s # dbg
675 676
676 677
677 678 # detail_level: 0 -> obj? , 1 -> obj??
678 679 detail_level = 0
679 680 # We need to detect if we got called as 'pinfo pinfo foo', which can
680 681 # happen if the user types 'pinfo foo?' at the cmd line.
681 682 pinfo,qmark1,oname,qmark2 = \
682 683 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
683 684 if pinfo or qmark1 or qmark2:
684 685 detail_level = 1
685 686 if "*" in oname:
686 687 self.magic_psearch(oname)
687 688 else:
688 689 self._inspect('pinfo', oname, detail_level=detail_level,
689 690 namespaces=namespaces)
690 691
691 692 def magic_pdef(self, parameter_s='', namespaces=None):
692 693 """Print the definition header for any callable object.
693 694
694 695 If the object is a class, print the constructor information."""
695 696 self._inspect('pdef',parameter_s, namespaces)
696 697
697 698 def magic_pdoc(self, parameter_s='', namespaces=None):
698 699 """Print the docstring for an object.
699 700
700 701 If the given object is a class, it will print both the class and the
701 702 constructor docstrings."""
702 703 self._inspect('pdoc',parameter_s, namespaces)
703 704
704 705 def magic_psource(self, parameter_s='', namespaces=None):
705 706 """Print (or run through pager) the source code for an object."""
706 707 self._inspect('psource',parameter_s, namespaces)
707 708
708 709 def magic_pfile(self, parameter_s=''):
709 710 """Print (or run through pager) the file where an object is defined.
710 711
711 712 The file opens at the line where the object definition begins. IPython
712 713 will honor the environment variable PAGER if set, and otherwise will
713 714 do its best to print the file in a convenient form.
714 715
715 716 If the given argument is not an object currently defined, IPython will
716 717 try to interpret it as a filename (automatically adding a .py extension
717 718 if needed). You can thus use %pfile as a syntax highlighting code
718 719 viewer."""
719 720
720 721 # first interpret argument as an object name
721 722 out = self._inspect('pfile',parameter_s)
722 723 # if not, try the input as a filename
723 724 if out == 'not found':
724 725 try:
725 726 filename = get_py_filename(parameter_s)
726 727 except IOError,msg:
727 728 print msg
728 729 return
729 730 page(self.shell.inspector.format(file(filename).read()))
730 731
731 732 def _inspect(self,meth,oname,namespaces=None,**kw):
732 733 """Generic interface to the inspector system.
733 734
734 735 This function is meant to be called by pdef, pdoc & friends."""
735 736
736 737 #oname = oname.strip()
737 738 #print '1- oname: <%r>' % oname # dbg
738 739 try:
739 740 oname = oname.strip().encode('ascii')
740 741 #print '2- oname: <%r>' % oname # dbg
741 742 except UnicodeEncodeError:
742 743 print 'Python identifiers can only contain ascii characters.'
743 744 return 'not found'
744 745
745 746 info = Struct(self._ofind(oname, namespaces))
746 747
747 748 if info.found:
748 749 try:
749 750 IPython.utils.generics.inspect_object(info.obj)
750 751 return
751 752 except TryNext:
752 753 pass
753 754 # Get the docstring of the class property if it exists.
754 755 path = oname.split('.')
755 756 root = '.'.join(path[:-1])
756 757 if info.parent is not None:
757 758 try:
758 759 target = getattr(info.parent, '__class__')
759 760 # The object belongs to a class instance.
760 761 try:
761 762 target = getattr(target, path[-1])
762 763 # The class defines the object.
763 764 if isinstance(target, property):
764 765 oname = root + '.__class__.' + path[-1]
765 766 info = Struct(self._ofind(oname))
766 767 except AttributeError: pass
767 768 except AttributeError: pass
768 769
769 770 pmethod = getattr(self.shell.inspector,meth)
770 771 formatter = info.ismagic and self.format_screen or None
771 772 if meth == 'pdoc':
772 773 pmethod(info.obj,oname,formatter)
773 774 elif meth == 'pinfo':
774 775 pmethod(info.obj,oname,formatter,info,**kw)
775 776 else:
776 777 pmethod(info.obj,oname)
777 778 else:
778 779 print 'Object `%s` not found.' % oname
779 780 return 'not found' # so callers can take other action
780 781
781 782 def magic_psearch(self, parameter_s=''):
782 783 """Search for object in namespaces by wildcard.
783 784
784 785 %psearch [options] PATTERN [OBJECT TYPE]
785 786
786 787 Note: ? can be used as a synonym for %psearch, at the beginning or at
787 788 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
788 789 rest of the command line must be unchanged (options come first), so
789 790 for example the following forms are equivalent
790 791
791 792 %psearch -i a* function
792 793 -i a* function?
793 794 ?-i a* function
794 795
795 796 Arguments:
796 797
797 798 PATTERN
798 799
799 800 where PATTERN is a string containing * as a wildcard similar to its
800 801 use in a shell. The pattern is matched in all namespaces on the
801 802 search path. By default objects starting with a single _ are not
802 803 matched, many IPython generated objects have a single
803 804 underscore. The default is case insensitive matching. Matching is
804 805 also done on the attributes of objects and not only on the objects
805 806 in a module.
806 807
807 808 [OBJECT TYPE]
808 809
809 810 Is the name of a python type from the types module. The name is
810 811 given in lowercase without the ending type, ex. StringType is
811 812 written string. By adding a type here only objects matching the
812 813 given type are matched. Using all here makes the pattern match all
813 814 types (this is the default).
814 815
815 816 Options:
816 817
817 818 -a: makes the pattern match even objects whose names start with a
818 819 single underscore. These names are normally ommitted from the
819 820 search.
820 821
821 822 -i/-c: make the pattern case insensitive/sensitive. If neither of
822 823 these options is given, the default is read from your ipythonrc
823 824 file. The option name which sets this value is
824 825 'wildcards_case_sensitive'. If this option is not specified in your
825 826 ipythonrc file, IPython's internal default is to do a case sensitive
826 827 search.
827 828
828 829 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
829 830 specifiy can be searched in any of the following namespaces:
830 831 'builtin', 'user', 'user_global','internal', 'alias', where
831 832 'builtin' and 'user' are the search defaults. Note that you should
832 833 not use quotes when specifying namespaces.
833 834
834 835 'Builtin' contains the python module builtin, 'user' contains all
835 836 user data, 'alias' only contain the shell aliases and no python
836 837 objects, 'internal' contains objects used by IPython. The
837 838 'user_global' namespace is only used by embedded IPython instances,
838 839 and it contains module-level globals. You can add namespaces to the
839 840 search with -s or exclude them with -e (these options can be given
840 841 more than once).
841 842
842 843 Examples:
843 844
844 845 %psearch a* -> objects beginning with an a
845 846 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
846 847 %psearch a* function -> all functions beginning with an a
847 848 %psearch re.e* -> objects beginning with an e in module re
848 849 %psearch r*.e* -> objects that start with e in modules starting in r
849 850 %psearch r*.* string -> all strings in modules beginning with r
850 851
851 852 Case sensitve search:
852 853
853 854 %psearch -c a* list all object beginning with lower case a
854 855
855 856 Show objects beginning with a single _:
856 857
857 858 %psearch -a _* list objects beginning with a single underscore"""
858 859 try:
859 860 parameter_s = parameter_s.encode('ascii')
860 861 except UnicodeEncodeError:
861 862 print 'Python identifiers can only contain ascii characters.'
862 863 return
863 864
864 865 # default namespaces to be searched
865 866 def_search = ['user','builtin']
866 867
867 868 # Process options/args
868 869 opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
869 870 opt = opts.get
870 871 shell = self.shell
871 872 psearch = shell.inspector.psearch
872 873
873 874 # select case options
874 875 if opts.has_key('i'):
875 876 ignore_case = True
876 877 elif opts.has_key('c'):
877 878 ignore_case = False
878 879 else:
879 880 ignore_case = not shell.wildcards_case_sensitive
880 881
881 882 # Build list of namespaces to search from user options
882 883 def_search.extend(opt('s',[]))
883 884 ns_exclude = ns_exclude=opt('e',[])
884 885 ns_search = [nm for nm in def_search if nm not in ns_exclude]
885 886
886 887 # Call the actual search
887 888 try:
888 889 psearch(args,shell.ns_table,ns_search,
889 890 show_all=opt('a'),ignore_case=ignore_case)
890 891 except:
891 892 shell.showtraceback()
892 893
893 894 def magic_who_ls(self, parameter_s=''):
894 895 """Return a sorted list of all interactive variables.
895 896
896 897 If arguments are given, only variables of types matching these
897 898 arguments are returned."""
898 899
899 900 user_ns = self.shell.user_ns
900 901 internal_ns = self.shell.internal_ns
901 902 user_ns_hidden = self.shell.user_ns_hidden
902 903 out = [ i for i in user_ns
903 904 if not i.startswith('_') \
904 905 and not (i in internal_ns or i in user_ns_hidden) ]
905 906
906 907 typelist = parameter_s.split()
907 908 if typelist:
908 909 typeset = set(typelist)
909 910 out = [i for i in out if type(i).__name__ in typeset]
910 911
911 912 out.sort()
912 913 return out
913 914
914 915 def magic_who(self, parameter_s=''):
915 916 """Print all interactive variables, with some minimal formatting.
916 917
917 918 If any arguments are given, only variables whose type matches one of
918 919 these are printed. For example:
919 920
920 921 %who function str
921 922
922 923 will only list functions and strings, excluding all other types of
923 924 variables. To find the proper type names, simply use type(var) at a
924 925 command line to see how python prints type names. For example:
925 926
926 927 In [1]: type('hello')\\
927 928 Out[1]: <type 'str'>
928 929
929 930 indicates that the type name for strings is 'str'.
930 931
931 932 %who always excludes executed names loaded through your configuration
932 933 file and things which are internal to IPython.
933 934
934 935 This is deliberate, as typically you may load many modules and the
935 936 purpose of %who is to show you only what you've manually defined."""
936 937
937 938 varlist = self.magic_who_ls(parameter_s)
938 939 if not varlist:
939 940 if parameter_s:
940 941 print 'No variables match your requested type.'
941 942 else:
942 943 print 'Interactive namespace is empty.'
943 944 return
944 945
945 946 # if we have variables, move on...
946 947 count = 0
947 948 for i in varlist:
948 949 print i+'\t',
949 950 count += 1
950 951 if count > 8:
951 952 count = 0
952 953 print
953 954 print
954 955
955 956 def magic_whos(self, parameter_s=''):
956 957 """Like %who, but gives some extra information about each variable.
957 958
958 959 The same type filtering of %who can be applied here.
959 960
960 961 For all variables, the type is printed. Additionally it prints:
961 962
962 963 - For {},[],(): their length.
963 964
964 965 - For numpy and Numeric arrays, a summary with shape, number of
965 966 elements, typecode and size in memory.
966 967
967 968 - Everything else: a string representation, snipping their middle if
968 969 too long."""
969 970
970 971 varnames = self.magic_who_ls(parameter_s)
971 972 if not varnames:
972 973 if parameter_s:
973 974 print 'No variables match your requested type.'
974 975 else:
975 976 print 'Interactive namespace is empty.'
976 977 return
977 978
978 979 # if we have variables, move on...
979 980
980 981 # for these types, show len() instead of data:
981 982 seq_types = [types.DictType,types.ListType,types.TupleType]
982 983
983 984 # for numpy/Numeric arrays, display summary info
984 985 try:
985 986 import numpy
986 987 except ImportError:
987 988 ndarray_type = None
988 989 else:
989 990 ndarray_type = numpy.ndarray.__name__
990 991 try:
991 992 import Numeric
992 993 except ImportError:
993 994 array_type = None
994 995 else:
995 996 array_type = Numeric.ArrayType.__name__
996 997
997 998 # Find all variable names and types so we can figure out column sizes
998 999 def get_vars(i):
999 1000 return self.shell.user_ns[i]
1000 1001
1001 1002 # some types are well known and can be shorter
1002 1003 abbrevs = {'IPython.core.macro.Macro' : 'Macro'}
1003 1004 def type_name(v):
1004 1005 tn = type(v).__name__
1005 1006 return abbrevs.get(tn,tn)
1006 1007
1007 1008 varlist = map(get_vars,varnames)
1008 1009
1009 1010 typelist = []
1010 1011 for vv in varlist:
1011 1012 tt = type_name(vv)
1012 1013
1013 1014 if tt=='instance':
1014 1015 typelist.append( abbrevs.get(str(vv.__class__),
1015 1016 str(vv.__class__)))
1016 1017 else:
1017 1018 typelist.append(tt)
1018 1019
1019 1020 # column labels and # of spaces as separator
1020 1021 varlabel = 'Variable'
1021 1022 typelabel = 'Type'
1022 1023 datalabel = 'Data/Info'
1023 1024 colsep = 3
1024 1025 # variable format strings
1025 1026 vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)"
1026 1027 vfmt_short = '$vstr[:25]<...>$vstr[-25:]'
1027 1028 aformat = "%s: %s elems, type `%s`, %s bytes"
1028 1029 # find the size of the columns to format the output nicely
1029 1030 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
1030 1031 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
1031 1032 # table header
1032 1033 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
1033 1034 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
1034 1035 # and the table itself
1035 1036 kb = 1024
1036 1037 Mb = 1048576 # kb**2
1037 1038 for vname,var,vtype in zip(varnames,varlist,typelist):
1038 1039 print itpl(vformat),
1039 1040 if vtype in seq_types:
1040 1041 print len(var)
1041 1042 elif vtype in [array_type,ndarray_type]:
1042 1043 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
1043 1044 if vtype==ndarray_type:
1044 1045 # numpy
1045 1046 vsize = var.size
1046 1047 vbytes = vsize*var.itemsize
1047 1048 vdtype = var.dtype
1048 1049 else:
1049 1050 # Numeric
1050 1051 vsize = Numeric.size(var)
1051 1052 vbytes = vsize*var.itemsize()
1052 1053 vdtype = var.typecode()
1053 1054
1054 1055 if vbytes < 100000:
1055 1056 print aformat % (vshape,vsize,vdtype,vbytes)
1056 1057 else:
1057 1058 print aformat % (vshape,vsize,vdtype,vbytes),
1058 1059 if vbytes < Mb:
1059 1060 print '(%s kb)' % (vbytes/kb,)
1060 1061 else:
1061 1062 print '(%s Mb)' % (vbytes/Mb,)
1062 1063 else:
1063 1064 try:
1064 1065 vstr = str(var)
1065 1066 except UnicodeEncodeError:
1066 1067 vstr = unicode(var).encode(sys.getdefaultencoding(),
1067 1068 'backslashreplace')
1068 1069 vstr = vstr.replace('\n','\\n')
1069 1070 if len(vstr) < 50:
1070 1071 print vstr
1071 1072 else:
1072 1073 printpl(vfmt_short)
1073 1074
1074 1075 def magic_reset(self, parameter_s=''):
1075 1076 """Resets the namespace by removing all names defined by the user.
1076 1077
1077 1078 Input/Output history are left around in case you need them.
1078 1079
1079 1080 Parameters
1080 1081 ----------
1081 1082 -y : force reset without asking for confirmation.
1082 1083
1083 1084 Examples
1084 1085 --------
1085 1086 In [6]: a = 1
1086 1087
1087 1088 In [7]: a
1088 1089 Out[7]: 1
1089 1090
1090 1091 In [8]: 'a' in _ip.user_ns
1091 1092 Out[8]: True
1092 1093
1093 1094 In [9]: %reset -f
1094 1095
1095 1096 In [10]: 'a' in _ip.user_ns
1096 1097 Out[10]: False
1097 1098 """
1098 1099
1099 1100 if parameter_s == '-f':
1100 1101 ans = True
1101 1102 else:
1102 1103 ans = self.shell.ask_yes_no(
1103 1104 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ")
1104 1105 if not ans:
1105 1106 print 'Nothing done.'
1106 1107 return
1107 1108 user_ns = self.shell.user_ns
1108 1109 for i in self.magic_who_ls():
1109 1110 del(user_ns[i])
1110 1111
1111 1112 # Also flush the private list of module references kept for script
1112 1113 # execution protection
1113 1114 self.shell.clear_main_mod_cache()
1114 1115
1115 1116 def magic_reset_selective(self, parameter_s=''):
1116 1117 """Resets the namespace by removing names defined by the user.
1117 1118
1118 1119 Input/Output history are left around in case you need them.
1119 1120
1120 1121 %reset_selective [-f] regex
1121 1122
1122 1123 No action is taken if regex is not included
1123 1124
1124 1125 Options
1125 1126 -f : force reset without asking for confirmation.
1126 1127
1127 1128 Examples
1128 1129 --------
1129 1130
1130 1131 We first fully reset the namespace so your output looks identical to
1131 1132 this example for pedagogical reasons; in practice you do not need a
1132 1133 full reset.
1133 1134
1134 1135 In [1]: %reset -f
1135 1136
1136 1137 Now, with a clean namespace we can make a few variables and use
1137 1138 %reset_selective to only delete names that match our regexp:
1138 1139
1139 1140 In [2]: a=1; b=2; c=3; b1m=4; b2m=5; b3m=6; b4m=7; b2s=8
1140 1141
1141 1142 In [3]: who_ls
1142 1143 Out[3]: ['a', 'b', 'b1m', 'b2m', 'b2s', 'b3m', 'b4m', 'c']
1143 1144
1144 1145 In [4]: %reset_selective -f b[2-3]m
1145 1146
1146 1147 In [5]: who_ls
1147 1148 Out[5]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c']
1148 1149
1149 1150 In [6]: %reset_selective -f d
1150 1151
1151 1152 In [7]: who_ls
1152 1153 Out[7]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c']
1153 1154
1154 1155 In [8]: %reset_selective -f c
1155 1156
1156 1157 In [9]: who_ls
1157 1158 Out[9]: ['a', 'b', 'b1m', 'b2s', 'b4m']
1158 1159
1159 1160 In [10]: %reset_selective -f b
1160 1161
1161 1162 In [11]: who_ls
1162 1163 Out[11]: ['a']
1163 1164 """
1164 1165
1165 1166 opts, regex = self.parse_options(parameter_s,'f')
1166 1167
1167 1168 if opts.has_key('f'):
1168 1169 ans = True
1169 1170 else:
1170 1171 ans = self.shell.ask_yes_no(
1171 1172 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ")
1172 1173 if not ans:
1173 1174 print 'Nothing done.'
1174 1175 return
1175 1176 user_ns = self.shell.user_ns
1176 1177 if not regex:
1177 1178 print 'No regex pattern specified. Nothing done.'
1178 1179 return
1179 1180 else:
1180 1181 try:
1181 1182 m = re.compile(regex)
1182 1183 except TypeError:
1183 1184 raise TypeError('regex must be a string or compiled pattern')
1184 1185 for i in self.magic_who_ls():
1185 1186 if m.search(i):
1186 1187 del(user_ns[i])
1187 1188
1188 1189 def magic_logstart(self,parameter_s=''):
1189 1190 """Start logging anywhere in a session.
1190 1191
1191 1192 %logstart [-o|-r|-t] [log_name [log_mode]]
1192 1193
1193 1194 If no name is given, it defaults to a file named 'ipython_log.py' in your
1194 1195 current directory, in 'rotate' mode (see below).
1195 1196
1196 1197 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
1197 1198 history up to that point and then continues logging.
1198 1199
1199 1200 %logstart takes a second optional parameter: logging mode. This can be one
1200 1201 of (note that the modes are given unquoted):\\
1201 1202 append: well, that says it.\\
1202 1203 backup: rename (if exists) to name~ and start name.\\
1203 1204 global: single logfile in your home dir, appended to.\\
1204 1205 over : overwrite existing log.\\
1205 1206 rotate: create rotating logs name.1~, name.2~, etc.
1206 1207
1207 1208 Options:
1208 1209
1209 1210 -o: log also IPython's output. In this mode, all commands which
1210 1211 generate an Out[NN] prompt are recorded to the logfile, right after
1211 1212 their corresponding input line. The output lines are always
1212 1213 prepended with a '#[Out]# ' marker, so that the log remains valid
1213 1214 Python code.
1214 1215
1215 1216 Since this marker is always the same, filtering only the output from
1216 1217 a log is very easy, using for example a simple awk call:
1217 1218
1218 1219 awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py
1219 1220
1220 1221 -r: log 'raw' input. Normally, IPython's logs contain the processed
1221 1222 input, so that user lines are logged in their final form, converted
1222 1223 into valid Python. For example, %Exit is logged as
1223 1224 '_ip.magic("Exit"). If the -r flag is given, all input is logged
1224 1225 exactly as typed, with no transformations applied.
1225 1226
1226 1227 -t: put timestamps before each input line logged (these are put in
1227 1228 comments)."""
1228 1229
1229 1230 opts,par = self.parse_options(parameter_s,'ort')
1230 1231 log_output = 'o' in opts
1231 1232 log_raw_input = 'r' in opts
1232 1233 timestamp = 't' in opts
1233 1234
1234 1235 logger = self.shell.logger
1235 1236
1236 1237 # if no args are given, the defaults set in the logger constructor by
1237 1238 # ipytohn remain valid
1238 1239 if par:
1239 1240 try:
1240 1241 logfname,logmode = par.split()
1241 1242 except:
1242 1243 logfname = par
1243 1244 logmode = 'backup'
1244 1245 else:
1245 1246 logfname = logger.logfname
1246 1247 logmode = logger.logmode
1247 1248 # put logfname into rc struct as if it had been called on the command
1248 1249 # line, so it ends up saved in the log header Save it in case we need
1249 1250 # to restore it...
1250 1251 old_logfile = self.shell.logfile
1251 1252 if logfname:
1252 1253 logfname = os.path.expanduser(logfname)
1253 1254 self.shell.logfile = logfname
1254 1255
1255 1256 loghead = '# IPython log file\n\n'
1256 1257 try:
1257 1258 started = logger.logstart(logfname,loghead,logmode,
1258 1259 log_output,timestamp,log_raw_input)
1259 1260 except:
1260 1261 self.shell.logfile = old_logfile
1261 1262 warn("Couldn't start log: %s" % sys.exc_info()[1])
1262 1263 else:
1263 1264 # log input history up to this point, optionally interleaving
1264 1265 # output if requested
1265 1266
1266 1267 if timestamp:
1267 1268 # disable timestamping for the previous history, since we've
1268 1269 # lost those already (no time machine here).
1269 1270 logger.timestamp = False
1270 1271
1271 1272 if log_raw_input:
1272 1273 input_hist = self.shell.input_hist_raw
1273 1274 else:
1274 1275 input_hist = self.shell.input_hist
1275 1276
1276 1277 if log_output:
1277 1278 log_write = logger.log_write
1278 1279 output_hist = self.shell.output_hist
1279 1280 for n in range(1,len(input_hist)-1):
1280 1281 log_write(input_hist[n].rstrip())
1281 1282 if n in output_hist:
1282 1283 log_write(repr(output_hist[n]),'output')
1283 1284 else:
1284 1285 logger.log_write(input_hist[1:])
1285 1286 if timestamp:
1286 1287 # re-enable timestamping
1287 1288 logger.timestamp = True
1288 1289
1289 1290 print ('Activating auto-logging. '
1290 1291 'Current session state plus future input saved.')
1291 1292 logger.logstate()
1292 1293
1293 1294 def magic_logstop(self,parameter_s=''):
1294 1295 """Fully stop logging and close log file.
1295 1296
1296 1297 In order to start logging again, a new %logstart call needs to be made,
1297 1298 possibly (though not necessarily) with a new filename, mode and other
1298 1299 options."""
1299 1300 self.logger.logstop()
1300 1301
1301 1302 def magic_logoff(self,parameter_s=''):
1302 1303 """Temporarily stop logging.
1303 1304
1304 1305 You must have previously started logging."""
1305 1306 self.shell.logger.switch_log(0)
1306 1307
1307 1308 def magic_logon(self,parameter_s=''):
1308 1309 """Restart logging.
1309 1310
1310 1311 This function is for restarting logging which you've temporarily
1311 1312 stopped with %logoff. For starting logging for the first time, you
1312 1313 must use the %logstart function, which allows you to specify an
1313 1314 optional log filename."""
1314 1315
1315 1316 self.shell.logger.switch_log(1)
1316 1317
1317 1318 def magic_logstate(self,parameter_s=''):
1318 1319 """Print the status of the logging system."""
1319 1320
1320 1321 self.shell.logger.logstate()
1321 1322
1322 1323 def magic_pdb(self, parameter_s=''):
1323 1324 """Control the automatic calling of the pdb interactive debugger.
1324 1325
1325 1326 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1326 1327 argument it works as a toggle.
1327 1328
1328 1329 When an exception is triggered, IPython can optionally call the
1329 1330 interactive pdb debugger after the traceback printout. %pdb toggles
1330 1331 this feature on and off.
1331 1332
1332 1333 The initial state of this feature is set in your ipythonrc
1333 1334 configuration file (the variable is called 'pdb').
1334 1335
1335 1336 If you want to just activate the debugger AFTER an exception has fired,
1336 1337 without having to type '%pdb on' and rerunning your code, you can use
1337 1338 the %debug magic."""
1338 1339
1339 1340 par = parameter_s.strip().lower()
1340 1341
1341 1342 if par:
1342 1343 try:
1343 1344 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
1344 1345 except KeyError:
1345 1346 print ('Incorrect argument. Use on/1, off/0, '
1346 1347 'or nothing for a toggle.')
1347 1348 return
1348 1349 else:
1349 1350 # toggle
1350 1351 new_pdb = not self.shell.call_pdb
1351 1352
1352 1353 # set on the shell
1353 1354 self.shell.call_pdb = new_pdb
1354 1355 print 'Automatic pdb calling has been turned',on_off(new_pdb)
1355 1356
1356 1357 def magic_debug(self, parameter_s=''):
1357 1358 """Activate the interactive debugger in post-mortem mode.
1358 1359
1359 1360 If an exception has just occurred, this lets you inspect its stack
1360 1361 frames interactively. Note that this will always work only on the last
1361 1362 traceback that occurred, so you must call this quickly after an
1362 1363 exception that you wish to inspect has fired, because if another one
1363 1364 occurs, it clobbers the previous one.
1364 1365
1365 1366 If you want IPython to automatically do this on every exception, see
1366 1367 the %pdb magic for more details.
1367 1368 """
1368 1369 self.shell.debugger(force=True)
1369 1370
1370 1371 @testdec.skip_doctest
1371 1372 def magic_prun(self, parameter_s ='',user_mode=1,
1372 1373 opts=None,arg_lst=None,prog_ns=None):
1373 1374
1374 1375 """Run a statement through the python code profiler.
1375 1376
1376 1377 Usage:
1377 1378 %prun [options] statement
1378 1379
1379 1380 The given statement (which doesn't require quote marks) is run via the
1380 1381 python profiler in a manner similar to the profile.run() function.
1381 1382 Namespaces are internally managed to work correctly; profile.run
1382 1383 cannot be used in IPython because it makes certain assumptions about
1383 1384 namespaces which do not hold under IPython.
1384 1385
1385 1386 Options:
1386 1387
1387 1388 -l <limit>: you can place restrictions on what or how much of the
1388 1389 profile gets printed. The limit value can be:
1389 1390
1390 1391 * A string: only information for function names containing this string
1391 1392 is printed.
1392 1393
1393 1394 * An integer: only these many lines are printed.
1394 1395
1395 1396 * A float (between 0 and 1): this fraction of the report is printed
1396 1397 (for example, use a limit of 0.4 to see the topmost 40% only).
1397 1398
1398 1399 You can combine several limits with repeated use of the option. For
1399 1400 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1400 1401 information about class constructors.
1401 1402
1402 1403 -r: return the pstats.Stats object generated by the profiling. This
1403 1404 object has all the information about the profile in it, and you can
1404 1405 later use it for further analysis or in other functions.
1405 1406
1406 1407 -s <key>: sort profile by given key. You can provide more than one key
1407 1408 by using the option several times: '-s key1 -s key2 -s key3...'. The
1408 1409 default sorting key is 'time'.
1409 1410
1410 1411 The following is copied verbatim from the profile documentation
1411 1412 referenced below:
1412 1413
1413 1414 When more than one key is provided, additional keys are used as
1414 1415 secondary criteria when the there is equality in all keys selected
1415 1416 before them.
1416 1417
1417 1418 Abbreviations can be used for any key names, as long as the
1418 1419 abbreviation is unambiguous. The following are the keys currently
1419 1420 defined:
1420 1421
1421 1422 Valid Arg Meaning
1422 1423 "calls" call count
1423 1424 "cumulative" cumulative time
1424 1425 "file" file name
1425 1426 "module" file name
1426 1427 "pcalls" primitive call count
1427 1428 "line" line number
1428 1429 "name" function name
1429 1430 "nfl" name/file/line
1430 1431 "stdname" standard name
1431 1432 "time" internal time
1432 1433
1433 1434 Note that all sorts on statistics are in descending order (placing
1434 1435 most time consuming items first), where as name, file, and line number
1435 1436 searches are in ascending order (i.e., alphabetical). The subtle
1436 1437 distinction between "nfl" and "stdname" is that the standard name is a
1437 1438 sort of the name as printed, which means that the embedded line
1438 1439 numbers get compared in an odd way. For example, lines 3, 20, and 40
1439 1440 would (if the file names were the same) appear in the string order
1440 1441 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1441 1442 line numbers. In fact, sort_stats("nfl") is the same as
1442 1443 sort_stats("name", "file", "line").
1443 1444
1444 1445 -T <filename>: save profile results as shown on screen to a text
1445 1446 file. The profile is still shown on screen.
1446 1447
1447 1448 -D <filename>: save (via dump_stats) profile statistics to given
1448 1449 filename. This data is in a format understod by the pstats module, and
1449 1450 is generated by a call to the dump_stats() method of profile
1450 1451 objects. The profile is still shown on screen.
1451 1452
1452 1453 If you want to run complete programs under the profiler's control, use
1453 1454 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1454 1455 contains profiler specific options as described here.
1455 1456
1456 1457 You can read the complete documentation for the profile module with::
1457 1458
1458 1459 In [1]: import profile; profile.help()
1459 1460 """
1460 1461
1461 1462 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1462 1463 # protect user quote marks
1463 1464 parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'")
1464 1465
1465 1466 if user_mode: # regular user call
1466 1467 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:',
1467 1468 list_all=1)
1468 1469 namespace = self.shell.user_ns
1469 1470 else: # called to run a program by %run -p
1470 1471 try:
1471 1472 filename = get_py_filename(arg_lst[0])
1472 1473 except IOError,msg:
1473 1474 error(msg)
1474 1475 return
1475 1476
1476 1477 arg_str = 'execfile(filename,prog_ns)'
1477 1478 namespace = locals()
1478 1479
1479 1480 opts.merge(opts_def)
1480 1481
1481 1482 prof = profile.Profile()
1482 1483 try:
1483 1484 prof = prof.runctx(arg_str,namespace,namespace)
1484 1485 sys_exit = ''
1485 1486 except SystemExit:
1486 1487 sys_exit = """*** SystemExit exception caught in code being profiled."""
1487 1488
1488 1489 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1489 1490
1490 1491 lims = opts.l
1491 1492 if lims:
1492 1493 lims = [] # rebuild lims with ints/floats/strings
1493 1494 for lim in opts.l:
1494 1495 try:
1495 1496 lims.append(int(lim))
1496 1497 except ValueError:
1497 1498 try:
1498 1499 lims.append(float(lim))
1499 1500 except ValueError:
1500 1501 lims.append(lim)
1501 1502
1502 1503 # Trap output.
1503 1504 stdout_trap = StringIO()
1504 1505
1505 1506 if hasattr(stats,'stream'):
1506 1507 # In newer versions of python, the stats object has a 'stream'
1507 1508 # attribute to write into.
1508 1509 stats.stream = stdout_trap
1509 1510 stats.print_stats(*lims)
1510 1511 else:
1511 1512 # For older versions, we manually redirect stdout during printing
1512 1513 sys_stdout = sys.stdout
1513 1514 try:
1514 1515 sys.stdout = stdout_trap
1515 1516 stats.print_stats(*lims)
1516 1517 finally:
1517 1518 sys.stdout = sys_stdout
1518 1519
1519 1520 output = stdout_trap.getvalue()
1520 1521 output = output.rstrip()
1521 1522
1522 1523 page(output,screen_lines=self.shell.usable_screen_length)
1523 1524 print sys_exit,
1524 1525
1525 1526 dump_file = opts.D[0]
1526 1527 text_file = opts.T[0]
1527 1528 if dump_file:
1528 1529 prof.dump_stats(dump_file)
1529 1530 print '\n*** Profile stats marshalled to file',\
1530 1531 `dump_file`+'.',sys_exit
1531 1532 if text_file:
1532 1533 pfile = file(text_file,'w')
1533 1534 pfile.write(output)
1534 1535 pfile.close()
1535 1536 print '\n*** Profile printout saved to text file',\
1536 1537 `text_file`+'.',sys_exit
1537 1538
1538 1539 if opts.has_key('r'):
1539 1540 return stats
1540 1541 else:
1541 1542 return None
1542 1543
1543 1544 @testdec.skip_doctest
1544 1545 def magic_run(self, parameter_s ='',runner=None,
1545 1546 file_finder=get_py_filename):
1546 1547 """Run the named file inside IPython as a program.
1547 1548
1548 1549 Usage:\\
1549 1550 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1550 1551
1551 1552 Parameters after the filename are passed as command-line arguments to
1552 1553 the program (put in sys.argv). Then, control returns to IPython's
1553 1554 prompt.
1554 1555
1555 1556 This is similar to running at a system prompt:\\
1556 1557 $ python file args\\
1557 1558 but with the advantage of giving you IPython's tracebacks, and of
1558 1559 loading all variables into your interactive namespace for further use
1559 1560 (unless -p is used, see below).
1560 1561
1561 1562 The file is executed in a namespace initially consisting only of
1562 1563 __name__=='__main__' and sys.argv constructed as indicated. It thus
1563 1564 sees its environment as if it were being run as a stand-alone program
1564 1565 (except for sharing global objects such as previously imported
1565 1566 modules). But after execution, the IPython interactive namespace gets
1566 1567 updated with all variables defined in the program (except for __name__
1567 1568 and sys.argv). This allows for very convenient loading of code for
1568 1569 interactive work, while giving each program a 'clean sheet' to run in.
1569 1570
1570 1571 Options:
1571 1572
1572 1573 -n: __name__ is NOT set to '__main__', but to the running file's name
1573 1574 without extension (as python does under import). This allows running
1574 1575 scripts and reloading the definitions in them without calling code
1575 1576 protected by an ' if __name__ == "__main__" ' clause.
1576 1577
1577 1578 -i: run the file in IPython's namespace instead of an empty one. This
1578 1579 is useful if you are experimenting with code written in a text editor
1579 1580 which depends on variables defined interactively.
1580 1581
1581 1582 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1582 1583 being run. This is particularly useful if IPython is being used to
1583 1584 run unittests, which always exit with a sys.exit() call. In such
1584 1585 cases you are interested in the output of the test results, not in
1585 1586 seeing a traceback of the unittest module.
1586 1587
1587 1588 -t: print timing information at the end of the run. IPython will give
1588 1589 you an estimated CPU time consumption for your script, which under
1589 1590 Unix uses the resource module to avoid the wraparound problems of
1590 1591 time.clock(). Under Unix, an estimate of time spent on system tasks
1591 1592 is also given (for Windows platforms this is reported as 0.0).
1592 1593
1593 1594 If -t is given, an additional -N<N> option can be given, where <N>
1594 1595 must be an integer indicating how many times you want the script to
1595 1596 run. The final timing report will include total and per run results.
1596 1597
1597 1598 For example (testing the script uniq_stable.py):
1598 1599
1599 1600 In [1]: run -t uniq_stable
1600 1601
1601 1602 IPython CPU timings (estimated):\\
1602 1603 User : 0.19597 s.\\
1603 1604 System: 0.0 s.\\
1604 1605
1605 1606 In [2]: run -t -N5 uniq_stable
1606 1607
1607 1608 IPython CPU timings (estimated):\\
1608 1609 Total runs performed: 5\\
1609 1610 Times : Total Per run\\
1610 1611 User : 0.910862 s, 0.1821724 s.\\
1611 1612 System: 0.0 s, 0.0 s.
1612 1613
1613 1614 -d: run your program under the control of pdb, the Python debugger.
1614 1615 This allows you to execute your program step by step, watch variables,
1615 1616 etc. Internally, what IPython does is similar to calling:
1616 1617
1617 1618 pdb.run('execfile("YOURFILENAME")')
1618 1619
1619 1620 with a breakpoint set on line 1 of your file. You can change the line
1620 1621 number for this automatic breakpoint to be <N> by using the -bN option
1621 1622 (where N must be an integer). For example:
1622 1623
1623 1624 %run -d -b40 myscript
1624 1625
1625 1626 will set the first breakpoint at line 40 in myscript.py. Note that
1626 1627 the first breakpoint must be set on a line which actually does
1627 1628 something (not a comment or docstring) for it to stop execution.
1628 1629
1629 1630 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1630 1631 first enter 'c' (without qoutes) to start execution up to the first
1631 1632 breakpoint.
1632 1633
1633 1634 Entering 'help' gives information about the use of the debugger. You
1634 1635 can easily see pdb's full documentation with "import pdb;pdb.help()"
1635 1636 at a prompt.
1636 1637
1637 1638 -p: run program under the control of the Python profiler module (which
1638 1639 prints a detailed report of execution times, function calls, etc).
1639 1640
1640 1641 You can pass other options after -p which affect the behavior of the
1641 1642 profiler itself. See the docs for %prun for details.
1642 1643
1643 1644 In this mode, the program's variables do NOT propagate back to the
1644 1645 IPython interactive namespace (because they remain in the namespace
1645 1646 where the profiler executes them).
1646 1647
1647 1648 Internally this triggers a call to %prun, see its documentation for
1648 1649 details on the options available specifically for profiling.
1649 1650
1650 1651 There is one special usage for which the text above doesn't apply:
1651 1652 if the filename ends with .ipy, the file is run as ipython script,
1652 1653 just as if the commands were written on IPython prompt.
1653 1654 """
1654 1655
1655 1656 # get arguments and set sys.argv for program to be run.
1656 1657 opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e',
1657 1658 mode='list',list_all=1)
1658 1659
1659 1660 try:
1660 1661 filename = file_finder(arg_lst[0])
1661 1662 except IndexError:
1662 1663 warn('you must provide at least a filename.')
1663 1664 print '\n%run:\n',oinspect.getdoc(self.magic_run)
1664 1665 return
1665 1666 except IOError,msg:
1666 1667 error(msg)
1667 1668 return
1668 1669
1669 1670 if filename.lower().endswith('.ipy'):
1670 1671 self.shell.safe_execfile_ipy(filename)
1671 1672 return
1672 1673
1673 1674 # Control the response to exit() calls made by the script being run
1674 1675 exit_ignore = opts.has_key('e')
1675 1676
1676 1677 # Make sure that the running script gets a proper sys.argv as if it
1677 1678 # were run from a system shell.
1678 1679 save_argv = sys.argv # save it for later restoring
1679 1680 sys.argv = [filename]+ arg_lst[1:] # put in the proper filename
1680 1681
1681 1682 if opts.has_key('i'):
1682 1683 # Run in user's interactive namespace
1683 1684 prog_ns = self.shell.user_ns
1684 1685 __name__save = self.shell.user_ns['__name__']
1685 1686 prog_ns['__name__'] = '__main__'
1686 1687 main_mod = self.shell.new_main_mod(prog_ns)
1687 1688 else:
1688 1689 # Run in a fresh, empty namespace
1689 1690 if opts.has_key('n'):
1690 1691 name = os.path.splitext(os.path.basename(filename))[0]
1691 1692 else:
1692 1693 name = '__main__'
1693 1694
1694 1695 main_mod = self.shell.new_main_mod()
1695 1696 prog_ns = main_mod.__dict__
1696 1697 prog_ns['__name__'] = name
1697 1698
1698 1699 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
1699 1700 # set the __file__ global in the script's namespace
1700 1701 prog_ns['__file__'] = filename
1701 1702
1702 1703 # pickle fix. See interactiveshell for an explanation. But we need to make sure
1703 1704 # that, if we overwrite __main__, we replace it at the end
1704 1705 main_mod_name = prog_ns['__name__']
1705 1706
1706 1707 if main_mod_name == '__main__':
1707 1708 restore_main = sys.modules['__main__']
1708 1709 else:
1709 1710 restore_main = False
1710 1711
1711 1712 # This needs to be undone at the end to prevent holding references to
1712 1713 # every single object ever created.
1713 1714 sys.modules[main_mod_name] = main_mod
1714 1715
1715 1716 stats = None
1716 1717 try:
1717 1718 self.shell.savehist()
1718 1719
1719 1720 if opts.has_key('p'):
1720 1721 stats = self.magic_prun('',0,opts,arg_lst,prog_ns)
1721 1722 else:
1722 1723 if opts.has_key('d'):
1723 1724 deb = debugger.Pdb(self.shell.colors)
1724 1725 # reset Breakpoint state, which is moronically kept
1725 1726 # in a class
1726 1727 bdb.Breakpoint.next = 1
1727 1728 bdb.Breakpoint.bplist = {}
1728 1729 bdb.Breakpoint.bpbynumber = [None]
1729 1730 # Set an initial breakpoint to stop execution
1730 1731 maxtries = 10
1731 1732 bp = int(opts.get('b',[1])[0])
1732 1733 checkline = deb.checkline(filename,bp)
1733 1734 if not checkline:
1734 1735 for bp in range(bp+1,bp+maxtries+1):
1735 1736 if deb.checkline(filename,bp):
1736 1737 break
1737 1738 else:
1738 1739 msg = ("\nI failed to find a valid line to set "
1739 1740 "a breakpoint\n"
1740 1741 "after trying up to line: %s.\n"
1741 1742 "Please set a valid breakpoint manually "
1742 1743 "with the -b option." % bp)
1743 1744 error(msg)
1744 1745 return
1745 1746 # if we find a good linenumber, set the breakpoint
1746 1747 deb.do_break('%s:%s' % (filename,bp))
1747 1748 # Start file run
1748 1749 print "NOTE: Enter 'c' at the",
1749 1750 print "%s prompt to start your script." % deb.prompt
1750 1751 try:
1751 1752 deb.run('execfile("%s")' % filename,prog_ns)
1752 1753
1753 1754 except:
1754 1755 etype, value, tb = sys.exc_info()
1755 1756 # Skip three frames in the traceback: the %run one,
1756 1757 # one inside bdb.py, and the command-line typed by the
1757 1758 # user (run by exec in pdb itself).
1758 1759 self.shell.InteractiveTB(etype,value,tb,tb_offset=3)
1759 1760 else:
1760 1761 if runner is None:
1761 1762 runner = self.shell.safe_execfile
1762 1763 if opts.has_key('t'):
1763 1764 # timed execution
1764 1765 try:
1765 1766 nruns = int(opts['N'][0])
1766 1767 if nruns < 1:
1767 1768 error('Number of runs must be >=1')
1768 1769 return
1769 1770 except (KeyError):
1770 1771 nruns = 1
1771 1772 if nruns == 1:
1772 1773 t0 = clock2()
1773 1774 runner(filename,prog_ns,prog_ns,
1774 1775 exit_ignore=exit_ignore)
1775 1776 t1 = clock2()
1776 1777 t_usr = t1[0]-t0[0]
1777 1778 t_sys = t1[1]-t0[1]
1778 1779 print "\nIPython CPU timings (estimated):"
1779 1780 print " User : %10s s." % t_usr
1780 1781 print " System: %10s s." % t_sys
1781 1782 else:
1782 1783 runs = range(nruns)
1783 1784 t0 = clock2()
1784 1785 for nr in runs:
1785 1786 runner(filename,prog_ns,prog_ns,
1786 1787 exit_ignore=exit_ignore)
1787 1788 t1 = clock2()
1788 1789 t_usr = t1[0]-t0[0]
1789 1790 t_sys = t1[1]-t0[1]
1790 1791 print "\nIPython CPU timings (estimated):"
1791 1792 print "Total runs performed:",nruns
1792 1793 print " Times : %10s %10s" % ('Total','Per run')
1793 1794 print " User : %10s s, %10s s." % (t_usr,t_usr/nruns)
1794 1795 print " System: %10s s, %10s s." % (t_sys,t_sys/nruns)
1795 1796
1796 1797 else:
1797 1798 # regular execution
1798 1799 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1799 1800
1800 1801 if opts.has_key('i'):
1801 1802 self.shell.user_ns['__name__'] = __name__save
1802 1803 else:
1803 1804 # The shell MUST hold a reference to prog_ns so after %run
1804 1805 # exits, the python deletion mechanism doesn't zero it out
1805 1806 # (leaving dangling references).
1806 1807 self.shell.cache_main_mod(prog_ns,filename)
1807 1808 # update IPython interactive namespace
1808 1809
1809 1810 # Some forms of read errors on the file may mean the
1810 1811 # __name__ key was never set; using pop we don't have to
1811 1812 # worry about a possible KeyError.
1812 1813 prog_ns.pop('__name__', None)
1813 1814
1814 1815 self.shell.user_ns.update(prog_ns)
1815 1816 finally:
1816 1817 # It's a bit of a mystery why, but __builtins__ can change from
1817 1818 # being a module to becoming a dict missing some key data after
1818 1819 # %run. As best I can see, this is NOT something IPython is doing
1819 1820 # at all, and similar problems have been reported before:
1820 1821 # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html
1821 1822 # Since this seems to be done by the interpreter itself, the best
1822 1823 # we can do is to at least restore __builtins__ for the user on
1823 1824 # exit.
1824 1825 self.shell.user_ns['__builtins__'] = __builtin__
1825 1826
1826 1827 # Ensure key global structures are restored
1827 1828 sys.argv = save_argv
1828 1829 if restore_main:
1829 1830 sys.modules['__main__'] = restore_main
1830 1831 else:
1831 1832 # Remove from sys.modules the reference to main_mod we'd
1832 1833 # added. Otherwise it will trap references to objects
1833 1834 # contained therein.
1834 1835 del sys.modules[main_mod_name]
1835 1836
1836 1837 self.shell.reloadhist()
1837 1838
1838 1839 return stats
1839 1840
1840 1841 @testdec.skip_doctest
1841 1842 def magic_timeit(self, parameter_s =''):
1842 1843 """Time execution of a Python statement or expression
1843 1844
1844 1845 Usage:\\
1845 1846 %timeit [-n<N> -r<R> [-t|-c]] statement
1846 1847
1847 1848 Time execution of a Python statement or expression using the timeit
1848 1849 module.
1849 1850
1850 1851 Options:
1851 1852 -n<N>: execute the given statement <N> times in a loop. If this value
1852 1853 is not given, a fitting value is chosen.
1853 1854
1854 1855 -r<R>: repeat the loop iteration <R> times and take the best result.
1855 1856 Default: 3
1856 1857
1857 1858 -t: use time.time to measure the time, which is the default on Unix.
1858 1859 This function measures wall time.
1859 1860
1860 1861 -c: use time.clock to measure the time, which is the default on
1861 1862 Windows and measures wall time. On Unix, resource.getrusage is used
1862 1863 instead and returns the CPU user time.
1863 1864
1864 1865 -p<P>: use a precision of <P> digits to display the timing result.
1865 1866 Default: 3
1866 1867
1867 1868
1868 1869 Examples:
1869 1870
1870 1871 In [1]: %timeit pass
1871 1872 10000000 loops, best of 3: 53.3 ns per loop
1872 1873
1873 1874 In [2]: u = None
1874 1875
1875 1876 In [3]: %timeit u is None
1876 1877 10000000 loops, best of 3: 184 ns per loop
1877 1878
1878 1879 In [4]: %timeit -r 4 u == None
1879 1880 1000000 loops, best of 4: 242 ns per loop
1880 1881
1881 1882 In [5]: import time
1882 1883
1883 1884 In [6]: %timeit -n1 time.sleep(2)
1884 1885 1 loops, best of 3: 2 s per loop
1885 1886
1886 1887
1887 1888 The times reported by %timeit will be slightly higher than those
1888 1889 reported by the timeit.py script when variables are accessed. This is
1889 1890 due to the fact that %timeit executes the statement in the namespace
1890 1891 of the shell, compared with timeit.py, which uses a single setup
1891 1892 statement to import function or create variables. Generally, the bias
1892 1893 does not matter as long as results from timeit.py are not mixed with
1893 1894 those from %timeit."""
1894 1895
1895 1896 import timeit
1896 1897 import math
1897 1898
1898 1899 # XXX: Unfortunately the unicode 'micro' symbol can cause problems in
1899 1900 # certain terminals. Until we figure out a robust way of
1900 1901 # auto-detecting if the terminal can deal with it, use plain 'us' for
1901 1902 # microseconds. I am really NOT happy about disabling the proper
1902 1903 # 'micro' prefix, but crashing is worse... If anyone knows what the
1903 1904 # right solution for this is, I'm all ears...
1904 1905 #
1905 1906 # Note: using
1906 1907 #
1907 1908 # s = u'\xb5'
1908 1909 # s.encode(sys.getdefaultencoding())
1909 1910 #
1910 1911 # is not sufficient, as I've seen terminals where that fails but
1911 1912 # print s
1912 1913 #
1913 1914 # succeeds
1914 1915 #
1915 1916 # See bug: https://bugs.launchpad.net/ipython/+bug/348466
1916 1917
1917 1918 #units = [u"s", u"ms",u'\xb5',"ns"]
1918 1919 units = [u"s", u"ms",u'us',"ns"]
1919 1920
1920 1921 scaling = [1, 1e3, 1e6, 1e9]
1921 1922
1922 1923 opts, stmt = self.parse_options(parameter_s,'n:r:tcp:',
1923 1924 posix=False)
1924 1925 if stmt == "":
1925 1926 return
1926 1927 timefunc = timeit.default_timer
1927 1928 number = int(getattr(opts, "n", 0))
1928 1929 repeat = int(getattr(opts, "r", timeit.default_repeat))
1929 1930 precision = int(getattr(opts, "p", 3))
1930 1931 if hasattr(opts, "t"):
1931 1932 timefunc = time.time
1932 1933 if hasattr(opts, "c"):
1933 1934 timefunc = clock
1934 1935
1935 1936 timer = timeit.Timer(timer=timefunc)
1936 1937 # this code has tight coupling to the inner workings of timeit.Timer,
1937 1938 # but is there a better way to achieve that the code stmt has access
1938 1939 # to the shell namespace?
1939 1940
1940 1941 src = timeit.template % {'stmt': timeit.reindent(stmt, 8),
1941 1942 'setup': "pass"}
1942 1943 # Track compilation time so it can be reported if too long
1943 1944 # Minimum time above which compilation time will be reported
1944 1945 tc_min = 0.1
1945 1946
1946 1947 t0 = clock()
1947 1948 code = compile(src, "<magic-timeit>", "exec")
1948 1949 tc = clock()-t0
1949 1950
1950 1951 ns = {}
1951 1952 exec code in self.shell.user_ns, ns
1952 1953 timer.inner = ns["inner"]
1953 1954
1954 1955 if number == 0:
1955 1956 # determine number so that 0.2 <= total time < 2.0
1956 1957 number = 1
1957 1958 for i in range(1, 10):
1958 1959 if timer.timeit(number) >= 0.2:
1959 1960 break
1960 1961 number *= 10
1961 1962
1962 1963 best = min(timer.repeat(repeat, number)) / number
1963 1964
1964 1965 if best > 0.0 and best < 1000.0:
1965 1966 order = min(-int(math.floor(math.log10(best)) // 3), 3)
1966 1967 elif best >= 1000.0:
1967 1968 order = 0
1968 1969 else:
1969 1970 order = 3
1970 1971 print u"%d loops, best of %d: %.*g %s per loop" % (number, repeat,
1971 1972 precision,
1972 1973 best * scaling[order],
1973 1974 units[order])
1974 1975 if tc > tc_min:
1975 1976 print "Compiler time: %.2f s" % tc
1976 1977
1977 1978 @testdec.skip_doctest
1978 1979 def magic_time(self,parameter_s = ''):
1979 1980 """Time execution of a Python statement or expression.
1980 1981
1981 1982 The CPU and wall clock times are printed, and the value of the
1982 1983 expression (if any) is returned. Note that under Win32, system time
1983 1984 is always reported as 0, since it can not be measured.
1984 1985
1985 1986 This function provides very basic timing functionality. In Python
1986 1987 2.3, the timeit module offers more control and sophistication, so this
1987 1988 could be rewritten to use it (patches welcome).
1988 1989
1989 1990 Some examples:
1990 1991
1991 1992 In [1]: time 2**128
1992 1993 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1993 1994 Wall time: 0.00
1994 1995 Out[1]: 340282366920938463463374607431768211456L
1995 1996
1996 1997 In [2]: n = 1000000
1997 1998
1998 1999 In [3]: time sum(range(n))
1999 2000 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
2000 2001 Wall time: 1.37
2001 2002 Out[3]: 499999500000L
2002 2003
2003 2004 In [4]: time print 'hello world'
2004 2005 hello world
2005 2006 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
2006 2007 Wall time: 0.00
2007 2008
2008 2009 Note that the time needed by Python to compile the given expression
2009 2010 will be reported if it is more than 0.1s. In this example, the
2010 2011 actual exponentiation is done by Python at compilation time, so while
2011 2012 the expression can take a noticeable amount of time to compute, that
2012 2013 time is purely due to the compilation:
2013 2014
2014 2015 In [5]: time 3**9999;
2015 2016 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
2016 2017 Wall time: 0.00 s
2017 2018
2018 2019 In [6]: time 3**999999;
2019 2020 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
2020 2021 Wall time: 0.00 s
2021 2022 Compiler : 0.78 s
2022 2023 """
2023 2024
2024 2025 # fail immediately if the given expression can't be compiled
2025 2026
2026 2027 expr = self.shell.prefilter(parameter_s,False)
2027 2028
2028 2029 # Minimum time above which compilation time will be reported
2029 2030 tc_min = 0.1
2030 2031
2031 2032 try:
2032 2033 mode = 'eval'
2033 2034 t0 = clock()
2034 2035 code = compile(expr,'<timed eval>',mode)
2035 2036 tc = clock()-t0
2036 2037 except SyntaxError:
2037 2038 mode = 'exec'
2038 2039 t0 = clock()
2039 2040 code = compile(expr,'<timed exec>',mode)
2040 2041 tc = clock()-t0
2041 2042 # skew measurement as little as possible
2042 2043 glob = self.shell.user_ns
2043 2044 clk = clock2
2044 2045 wtime = time.time
2045 2046 # time execution
2046 2047 wall_st = wtime()
2047 2048 if mode=='eval':
2048 2049 st = clk()
2049 2050 out = eval(code,glob)
2050 2051 end = clk()
2051 2052 else:
2052 2053 st = clk()
2053 2054 exec code in glob
2054 2055 end = clk()
2055 2056 out = None
2056 2057 wall_end = wtime()
2057 2058 # Compute actual times and report
2058 2059 wall_time = wall_end-wall_st
2059 2060 cpu_user = end[0]-st[0]
2060 2061 cpu_sys = end[1]-st[1]
2061 2062 cpu_tot = cpu_user+cpu_sys
2062 2063 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
2063 2064 (cpu_user,cpu_sys,cpu_tot)
2064 2065 print "Wall time: %.2f s" % wall_time
2065 2066 if tc > tc_min:
2066 2067 print "Compiler : %.2f s" % tc
2067 2068 return out
2068 2069
2069 2070 @testdec.skip_doctest
2070 2071 def magic_macro(self,parameter_s = ''):
2071 2072 """Define a set of input lines as a macro for future re-execution.
2072 2073
2073 2074 Usage:\\
2074 2075 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
2075 2076
2076 2077 Options:
2077 2078
2078 2079 -r: use 'raw' input. By default, the 'processed' history is used,
2079 2080 so that magics are loaded in their transformed version to valid
2080 2081 Python. If this option is given, the raw input as typed as the
2081 2082 command line is used instead.
2082 2083
2083 2084 This will define a global variable called `name` which is a string
2084 2085 made of joining the slices and lines you specify (n1,n2,... numbers
2085 2086 above) from your input history into a single string. This variable
2086 2087 acts like an automatic function which re-executes those lines as if
2087 2088 you had typed them. You just type 'name' at the prompt and the code
2088 2089 executes.
2089 2090
2090 2091 The notation for indicating number ranges is: n1-n2 means 'use line
2091 2092 numbers n1,...n2' (the endpoint is included). That is, '5-7' means
2092 2093 using the lines numbered 5,6 and 7.
2093 2094
2094 2095 Note: as a 'hidden' feature, you can also use traditional python slice
2095 2096 notation, where N:M means numbers N through M-1.
2096 2097
2097 2098 For example, if your history contains (%hist prints it):
2098 2099
2099 2100 44: x=1
2100 2101 45: y=3
2101 2102 46: z=x+y
2102 2103 47: print x
2103 2104 48: a=5
2104 2105 49: print 'x',x,'y',y
2105 2106
2106 2107 you can create a macro with lines 44 through 47 (included) and line 49
2107 2108 called my_macro with:
2108 2109
2109 2110 In [55]: %macro my_macro 44-47 49
2110 2111
2111 2112 Now, typing `my_macro` (without quotes) will re-execute all this code
2112 2113 in one pass.
2113 2114
2114 2115 You don't need to give the line-numbers in order, and any given line
2115 2116 number can appear multiple times. You can assemble macros with any
2116 2117 lines from your input history in any order.
2117 2118
2118 2119 The macro is a simple object which holds its value in an attribute,
2119 2120 but IPython's display system checks for macros and executes them as
2120 2121 code instead of printing them when you type their name.
2121 2122
2122 2123 You can view a macro's contents by explicitly printing it with:
2123 2124
2124 2125 'print macro_name'.
2125 2126
2126 2127 For one-off cases which DON'T contain magic function calls in them you
2127 2128 can obtain similar results by explicitly executing slices from your
2128 2129 input history with:
2129 2130
2130 2131 In [60]: exec In[44:48]+In[49]"""
2131 2132
2132 2133 opts,args = self.parse_options(parameter_s,'r',mode='list')
2133 2134 if not args:
2134 2135 macs = [k for k,v in self.shell.user_ns.items() if isinstance(v, Macro)]
2135 2136 macs.sort()
2136 2137 return macs
2137 2138 if len(args) == 1:
2138 2139 raise UsageError(
2139 2140 "%macro insufficient args; usage '%macro name n1-n2 n3-4...")
2140 2141 name,ranges = args[0], args[1:]
2141 2142
2142 2143 #print 'rng',ranges # dbg
2143 2144 lines = self.extract_input_slices(ranges,opts.has_key('r'))
2144 2145 macro = Macro(lines)
2145 2146 self.shell.define_macro(name, macro)
2146 2147 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
2147 2148 print 'Macro contents:'
2148 2149 print macro,
2149 2150
2150 2151 def magic_save(self,parameter_s = ''):
2151 2152 """Save a set of lines to a given filename.
2152 2153
2153 2154 Usage:\\
2154 2155 %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ...
2155 2156
2156 2157 Options:
2157 2158
2158 2159 -r: use 'raw' input. By default, the 'processed' history is used,
2159 2160 so that magics are loaded in their transformed version to valid
2160 2161 Python. If this option is given, the raw input as typed as the
2161 2162 command line is used instead.
2162 2163
2163 2164 This function uses the same syntax as %macro for line extraction, but
2164 2165 instead of creating a macro it saves the resulting string to the
2165 2166 filename you specify.
2166 2167
2167 2168 It adds a '.py' extension to the file if you don't do so yourself, and
2168 2169 it asks for confirmation before overwriting existing files."""
2169 2170
2170 2171 opts,args = self.parse_options(parameter_s,'r',mode='list')
2171 2172 fname,ranges = args[0], args[1:]
2172 2173 if not fname.endswith('.py'):
2173 2174 fname += '.py'
2174 2175 if os.path.isfile(fname):
2175 2176 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
2176 2177 if ans.lower() not in ['y','yes']:
2177 2178 print 'Operation cancelled.'
2178 2179 return
2179 2180 cmds = ''.join(self.extract_input_slices(ranges,opts.has_key('r')))
2180 2181 f = file(fname,'w')
2181 2182 f.write(cmds)
2182 2183 f.close()
2183 2184 print 'The following commands were written to file `%s`:' % fname
2184 2185 print cmds
2185 2186
2186 2187 def _edit_macro(self,mname,macro):
2187 2188 """open an editor with the macro data in a file"""
2188 2189 filename = self.shell.mktempfile(macro.value)
2189 2190 self.shell.hooks.editor(filename)
2190 2191
2191 2192 # and make a new macro object, to replace the old one
2192 2193 mfile = open(filename)
2193 2194 mvalue = mfile.read()
2194 2195 mfile.close()
2195 2196 self.shell.user_ns[mname] = Macro(mvalue)
2196 2197
2197 2198 def magic_ed(self,parameter_s=''):
2198 2199 """Alias to %edit."""
2199 2200 return self.magic_edit(parameter_s)
2200 2201
2201 2202 @testdec.skip_doctest
2202 2203 def magic_edit(self,parameter_s='',last_call=['','']):
2203 2204 """Bring up an editor and execute the resulting code.
2204 2205
2205 2206 Usage:
2206 2207 %edit [options] [args]
2207 2208
2208 2209 %edit runs IPython's editor hook. The default version of this hook is
2209 2210 set to call the __IPYTHON__.rc.editor command. This is read from your
2210 2211 environment variable $EDITOR. If this isn't found, it will default to
2211 2212 vi under Linux/Unix and to notepad under Windows. See the end of this
2212 2213 docstring for how to change the editor hook.
2213 2214
2214 2215 You can also set the value of this editor via the command line option
2215 2216 '-editor' or in your ipythonrc file. This is useful if you wish to use
2216 2217 specifically for IPython an editor different from your typical default
2217 2218 (and for Windows users who typically don't set environment variables).
2218 2219
2219 2220 This command allows you to conveniently edit multi-line code right in
2220 2221 your IPython session.
2221 2222
2222 2223 If called without arguments, %edit opens up an empty editor with a
2223 2224 temporary file and will execute the contents of this file when you
2224 2225 close it (don't forget to save it!).
2225 2226
2226 2227
2227 2228 Options:
2228 2229
2229 2230 -n <number>: open the editor at a specified line number. By default,
2230 2231 the IPython editor hook uses the unix syntax 'editor +N filename', but
2231 2232 you can configure this by providing your own modified hook if your
2232 2233 favorite editor supports line-number specifications with a different
2233 2234 syntax.
2234 2235
2235 2236 -p: this will call the editor with the same data as the previous time
2236 2237 it was used, regardless of how long ago (in your current session) it
2237 2238 was.
2238 2239
2239 2240 -r: use 'raw' input. This option only applies to input taken from the
2240 2241 user's history. By default, the 'processed' history is used, so that
2241 2242 magics are loaded in their transformed version to valid Python. If
2242 2243 this option is given, the raw input as typed as the command line is
2243 2244 used instead. When you exit the editor, it will be executed by
2244 2245 IPython's own processor.
2245 2246
2246 2247 -x: do not execute the edited code immediately upon exit. This is
2247 2248 mainly useful if you are editing programs which need to be called with
2248 2249 command line arguments, which you can then do using %run.
2249 2250
2250 2251
2251 2252 Arguments:
2252 2253
2253 2254 If arguments are given, the following possibilites exist:
2254 2255
2255 2256 - The arguments are numbers or pairs of colon-separated numbers (like
2256 2257 1 4:8 9). These are interpreted as lines of previous input to be
2257 2258 loaded into the editor. The syntax is the same of the %macro command.
2258 2259
2259 2260 - If the argument doesn't start with a number, it is evaluated as a
2260 2261 variable and its contents loaded into the editor. You can thus edit
2261 2262 any string which contains python code (including the result of
2262 2263 previous edits).
2263 2264
2264 2265 - If the argument is the name of an object (other than a string),
2265 2266 IPython will try to locate the file where it was defined and open the
2266 2267 editor at the point where it is defined. You can use `%edit function`
2267 2268 to load an editor exactly at the point where 'function' is defined,
2268 2269 edit it and have the file be executed automatically.
2269 2270
2270 2271 If the object is a macro (see %macro for details), this opens up your
2271 2272 specified editor with a temporary file containing the macro's data.
2272 2273 Upon exit, the macro is reloaded with the contents of the file.
2273 2274
2274 2275 Note: opening at an exact line is only supported under Unix, and some
2275 2276 editors (like kedit and gedit up to Gnome 2.8) do not understand the
2276 2277 '+NUMBER' parameter necessary for this feature. Good editors like
2277 2278 (X)Emacs, vi, jed, pico and joe all do.
2278 2279
2279 2280 - If the argument is not found as a variable, IPython will look for a
2280 2281 file with that name (adding .py if necessary) and load it into the
2281 2282 editor. It will execute its contents with execfile() when you exit,
2282 2283 loading any code in the file into your interactive namespace.
2283 2284
2284 2285 After executing your code, %edit will return as output the code you
2285 2286 typed in the editor (except when it was an existing file). This way
2286 2287 you can reload the code in further invocations of %edit as a variable,
2287 2288 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
2288 2289 the output.
2289 2290
2290 2291 Note that %edit is also available through the alias %ed.
2291 2292
2292 2293 This is an example of creating a simple function inside the editor and
2293 2294 then modifying it. First, start up the editor:
2294 2295
2295 2296 In [1]: ed
2296 2297 Editing... done. Executing edited code...
2297 2298 Out[1]: 'def foo():n print "foo() was defined in an editing session"n'
2298 2299
2299 2300 We can then call the function foo():
2300 2301
2301 2302 In [2]: foo()
2302 2303 foo() was defined in an editing session
2303 2304
2304 2305 Now we edit foo. IPython automatically loads the editor with the
2305 2306 (temporary) file where foo() was previously defined:
2306 2307
2307 2308 In [3]: ed foo
2308 2309 Editing... done. Executing edited code...
2309 2310
2310 2311 And if we call foo() again we get the modified version:
2311 2312
2312 2313 In [4]: foo()
2313 2314 foo() has now been changed!
2314 2315
2315 2316 Here is an example of how to edit a code snippet successive
2316 2317 times. First we call the editor:
2317 2318
2318 2319 In [5]: ed
2319 2320 Editing... done. Executing edited code...
2320 2321 hello
2321 2322 Out[5]: "print 'hello'n"
2322 2323
2323 2324 Now we call it again with the previous output (stored in _):
2324 2325
2325 2326 In [6]: ed _
2326 2327 Editing... done. Executing edited code...
2327 2328 hello world
2328 2329 Out[6]: "print 'hello world'n"
2329 2330
2330 2331 Now we call it with the output #8 (stored in _8, also as Out[8]):
2331 2332
2332 2333 In [7]: ed _8
2333 2334 Editing... done. Executing edited code...
2334 2335 hello again
2335 2336 Out[7]: "print 'hello again'n"
2336 2337
2337 2338
2338 2339 Changing the default editor hook:
2339 2340
2340 2341 If you wish to write your own editor hook, you can put it in a
2341 2342 configuration file which you load at startup time. The default hook
2342 2343 is defined in the IPython.core.hooks module, and you can use that as a
2343 2344 starting example for further modifications. That file also has
2344 2345 general instructions on how to set a new hook for use once you've
2345 2346 defined it."""
2346 2347
2347 2348 # FIXME: This function has become a convoluted mess. It needs a
2348 2349 # ground-up rewrite with clean, simple logic.
2349 2350
2350 2351 def make_filename(arg):
2351 2352 "Make a filename from the given args"
2352 2353 try:
2353 2354 filename = get_py_filename(arg)
2354 2355 except IOError:
2355 2356 if args.endswith('.py'):
2356 2357 filename = arg
2357 2358 else:
2358 2359 filename = None
2359 2360 return filename
2360 2361
2361 2362 # custom exceptions
2362 2363 class DataIsObject(Exception): pass
2363 2364
2364 2365 opts,args = self.parse_options(parameter_s,'prxn:')
2365 2366 # Set a few locals from the options for convenience:
2366 2367 opts_p = opts.has_key('p')
2367 2368 opts_r = opts.has_key('r')
2368 2369
2369 2370 # Default line number value
2370 2371 lineno = opts.get('n',None)
2371 2372
2372 2373 if opts_p:
2373 2374 args = '_%s' % last_call[0]
2374 2375 if not self.shell.user_ns.has_key(args):
2375 2376 args = last_call[1]
2376 2377
2377 2378 # use last_call to remember the state of the previous call, but don't
2378 2379 # let it be clobbered by successive '-p' calls.
2379 2380 try:
2380 2381 last_call[0] = self.shell.outputcache.prompt_count
2381 2382 if not opts_p:
2382 2383 last_call[1] = parameter_s
2383 2384 except:
2384 2385 pass
2385 2386
2386 2387 # by default this is done with temp files, except when the given
2387 2388 # arg is a filename
2388 2389 use_temp = 1
2389 2390
2390 2391 if re.match(r'\d',args):
2391 2392 # Mode where user specifies ranges of lines, like in %macro.
2392 2393 # This means that you can't edit files whose names begin with
2393 2394 # numbers this way. Tough.
2394 2395 ranges = args.split()
2395 2396 data = ''.join(self.extract_input_slices(ranges,opts_r))
2396 2397 elif args.endswith('.py'):
2397 2398 filename = make_filename(args)
2398 2399 data = ''
2399 2400 use_temp = 0
2400 2401 elif args:
2401 2402 try:
2402 2403 # Load the parameter given as a variable. If not a string,
2403 2404 # process it as an object instead (below)
2404 2405
2405 2406 #print '*** args',args,'type',type(args) # dbg
2406 2407 data = eval(args,self.shell.user_ns)
2407 2408 if not type(data) in StringTypes:
2408 2409 raise DataIsObject
2409 2410
2410 2411 except (NameError,SyntaxError):
2411 2412 # given argument is not a variable, try as a filename
2412 2413 filename = make_filename(args)
2413 2414 if filename is None:
2414 2415 warn("Argument given (%s) can't be found as a variable "
2415 2416 "or as a filename." % args)
2416 2417 return
2417 2418
2418 2419 data = ''
2419 2420 use_temp = 0
2420 2421 except DataIsObject:
2421 2422
2422 2423 # macros have a special edit function
2423 2424 if isinstance(data,Macro):
2424 2425 self._edit_macro(args,data)
2425 2426 return
2426 2427
2427 2428 # For objects, try to edit the file where they are defined
2428 2429 try:
2429 2430 filename = inspect.getabsfile(data)
2430 2431 if 'fakemodule' in filename.lower() and inspect.isclass(data):
2431 2432 # class created by %edit? Try to find source
2432 2433 # by looking for method definitions instead, the
2433 2434 # __module__ in those classes is FakeModule.
2434 2435 attrs = [getattr(data, aname) for aname in dir(data)]
2435 2436 for attr in attrs:
2436 2437 if not inspect.ismethod(attr):
2437 2438 continue
2438 2439 filename = inspect.getabsfile(attr)
2439 2440 if filename and 'fakemodule' not in filename.lower():
2440 2441 # change the attribute to be the edit target instead
2441 2442 data = attr
2442 2443 break
2443 2444
2444 2445 datafile = 1
2445 2446 except TypeError:
2446 2447 filename = make_filename(args)
2447 2448 datafile = 1
2448 2449 warn('Could not find file where `%s` is defined.\n'
2449 2450 'Opening a file named `%s`' % (args,filename))
2450 2451 # Now, make sure we can actually read the source (if it was in
2451 2452 # a temp file it's gone by now).
2452 2453 if datafile:
2453 2454 try:
2454 2455 if lineno is None:
2455 2456 lineno = inspect.getsourcelines(data)[1]
2456 2457 except IOError:
2457 2458 filename = make_filename(args)
2458 2459 if filename is None:
2459 2460 warn('The file `%s` where `%s` was defined cannot '
2460 2461 'be read.' % (filename,data))
2461 2462 return
2462 2463 use_temp = 0
2463 2464 else:
2464 2465 data = ''
2465 2466
2466 2467 if use_temp:
2467 2468 filename = self.shell.mktempfile(data)
2468 2469 print 'IPython will make a temporary file named:',filename
2469 2470
2470 2471 # do actual editing here
2471 2472 print 'Editing...',
2472 2473 sys.stdout.flush()
2473 2474 try:
2474 2475 # Quote filenames that may have spaces in them
2475 2476 if ' ' in filename:
2476 2477 filename = "%s" % filename
2477 2478 self.shell.hooks.editor(filename,lineno)
2478 2479 except TryNext:
2479 2480 warn('Could not open editor')
2480 2481 return
2481 2482
2482 2483 # XXX TODO: should this be generalized for all string vars?
2483 2484 # For now, this is special-cased to blocks created by cpaste
2484 2485 if args.strip() == 'pasted_block':
2485 2486 self.shell.user_ns['pasted_block'] = file_read(filename)
2486 2487
2487 2488 if opts.has_key('x'): # -x prevents actual execution
2488 2489 print
2489 2490 else:
2490 2491 print 'done. Executing edited code...'
2491 2492 if opts_r:
2492 2493 self.shell.runlines(file_read(filename))
2493 2494 else:
2494 2495 self.shell.safe_execfile(filename,self.shell.user_ns,
2495 2496 self.shell.user_ns)
2496 2497
2497 2498
2498 2499 if use_temp:
2499 2500 try:
2500 2501 return open(filename).read()
2501 2502 except IOError,msg:
2502 2503 if msg.filename == filename:
2503 2504 warn('File not found. Did you forget to save?')
2504 2505 return
2505 2506 else:
2506 2507 self.shell.showtraceback()
2507 2508
2508 2509 def magic_xmode(self,parameter_s = ''):
2509 2510 """Switch modes for the exception handlers.
2510 2511
2511 2512 Valid modes: Plain, Context and Verbose.
2512 2513
2513 2514 If called without arguments, acts as a toggle."""
2514 2515
2515 2516 def xmode_switch_err(name):
2516 2517 warn('Error changing %s exception modes.\n%s' %
2517 2518 (name,sys.exc_info()[1]))
2518 2519
2519 2520 shell = self.shell
2520 2521 new_mode = parameter_s.strip().capitalize()
2521 2522 try:
2522 2523 shell.InteractiveTB.set_mode(mode=new_mode)
2523 2524 print 'Exception reporting mode:',shell.InteractiveTB.mode
2524 2525 except:
2525 2526 xmode_switch_err('user')
2526 2527
2527 2528 def magic_colors(self,parameter_s = ''):
2528 2529 """Switch color scheme for prompts, info system and exception handlers.
2529 2530
2530 2531 Currently implemented schemes: NoColor, Linux, LightBG.
2531 2532
2532 2533 Color scheme names are not case-sensitive."""
2533 2534
2534 2535 def color_switch_err(name):
2535 2536 warn('Error changing %s color schemes.\n%s' %
2536 2537 (name,sys.exc_info()[1]))
2537 2538
2538 2539
2539 2540 new_scheme = parameter_s.strip()
2540 2541 if not new_scheme:
2541 2542 raise UsageError(
2542 2543 "%colors: you must specify a color scheme. See '%colors?'")
2543 2544 return
2544 2545 # local shortcut
2545 2546 shell = self.shell
2546 2547
2547 2548 import IPython.utils.rlineimpl as readline
2548 2549
2549 2550 if not readline.have_readline and sys.platform == "win32":
2550 2551 msg = """\
2551 2552 Proper color support under MS Windows requires the pyreadline library.
2552 2553 You can find it at:
2553 2554 http://ipython.scipy.org/moin/PyReadline/Intro
2554 2555 Gary's readline needs the ctypes module, from:
2555 2556 http://starship.python.net/crew/theller/ctypes
2556 2557 (Note that ctypes is already part of Python versions 2.5 and newer).
2557 2558
2558 2559 Defaulting color scheme to 'NoColor'"""
2559 2560 new_scheme = 'NoColor'
2560 2561 warn(msg)
2561 2562
2562 2563 # readline option is 0
2563 2564 if not shell.has_readline:
2564 2565 new_scheme = 'NoColor'
2565 2566
2566 2567 # Set prompt colors
2567 2568 try:
2568 2569 shell.outputcache.set_colors(new_scheme)
2569 2570 except:
2570 2571 color_switch_err('prompt')
2571 2572 else:
2572 2573 shell.colors = \
2573 2574 shell.outputcache.color_table.active_scheme_name
2574 2575 # Set exception colors
2575 2576 try:
2576 2577 shell.InteractiveTB.set_colors(scheme = new_scheme)
2577 2578 shell.SyntaxTB.set_colors(scheme = new_scheme)
2578 2579 except:
2579 2580 color_switch_err('exception')
2580 2581
2581 2582 # Set info (for 'object?') colors
2582 2583 if shell.color_info:
2583 2584 try:
2584 2585 shell.inspector.set_active_scheme(new_scheme)
2585 2586 except:
2586 2587 color_switch_err('object inspector')
2587 2588 else:
2588 2589 shell.inspector.set_active_scheme('NoColor')
2589 2590
2590 2591 def magic_color_info(self,parameter_s = ''):
2591 2592 """Toggle color_info.
2592 2593
2593 2594 The color_info configuration parameter controls whether colors are
2594 2595 used for displaying object details (by things like %psource, %pfile or
2595 2596 the '?' system). This function toggles this value with each call.
2596 2597
2597 2598 Note that unless you have a fairly recent pager (less works better
2598 2599 than more) in your system, using colored object information displays
2599 2600 will not work properly. Test it and see."""
2600 2601
2601 2602 self.shell.color_info = not self.shell.color_info
2602 2603 self.magic_colors(self.shell.colors)
2603 2604 print 'Object introspection functions have now coloring:',
2604 2605 print ['OFF','ON'][int(self.shell.color_info)]
2605 2606
2606 2607 def magic_Pprint(self, parameter_s=''):
2607 2608 """Toggle pretty printing on/off."""
2608 2609
2609 2610 self.shell.pprint = 1 - self.shell.pprint
2610 2611 print 'Pretty printing has been turned', \
2611 2612 ['OFF','ON'][self.shell.pprint]
2612 2613
2613 2614 def magic_Exit(self, parameter_s=''):
2614 2615 """Exit IPython without confirmation."""
2615 2616
2616 2617 self.shell.ask_exit()
2617 2618
2618 2619 # Add aliases as magics so all common forms work: exit, quit, Exit, Quit.
2619 2620 magic_exit = magic_quit = magic_Quit = magic_Exit
2620 2621
2621 2622 #......................................................................
2622 2623 # Functions to implement unix shell-type things
2623 2624
2624 2625 @testdec.skip_doctest
2625 2626 def magic_alias(self, parameter_s = ''):
2626 2627 """Define an alias for a system command.
2627 2628
2628 2629 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
2629 2630
2630 2631 Then, typing 'alias_name params' will execute the system command 'cmd
2631 2632 params' (from your underlying operating system).
2632 2633
2633 2634 Aliases have lower precedence than magic functions and Python normal
2634 2635 variables, so if 'foo' is both a Python variable and an alias, the
2635 2636 alias can not be executed until 'del foo' removes the Python variable.
2636 2637
2637 2638 You can use the %l specifier in an alias definition to represent the
2638 2639 whole line when the alias is called. For example:
2639 2640
2640 2641 In [2]: alias all echo "Input in brackets: <%l>"
2641 2642 In [3]: all hello world
2642 2643 Input in brackets: <hello world>
2643 2644
2644 2645 You can also define aliases with parameters using %s specifiers (one
2645 2646 per parameter):
2646 2647
2647 2648 In [1]: alias parts echo first %s second %s
2648 2649 In [2]: %parts A B
2649 2650 first A second B
2650 2651 In [3]: %parts A
2651 2652 Incorrect number of arguments: 2 expected.
2652 2653 parts is an alias to: 'echo first %s second %s'
2653 2654
2654 2655 Note that %l and %s are mutually exclusive. You can only use one or
2655 2656 the other in your aliases.
2656 2657
2657 2658 Aliases expand Python variables just like system calls using ! or !!
2658 2659 do: all expressions prefixed with '$' get expanded. For details of
2659 2660 the semantic rules, see PEP-215:
2660 2661 http://www.python.org/peps/pep-0215.html. This is the library used by
2661 2662 IPython for variable expansion. If you want to access a true shell
2662 2663 variable, an extra $ is necessary to prevent its expansion by IPython:
2663 2664
2664 2665 In [6]: alias show echo
2665 2666 In [7]: PATH='A Python string'
2666 2667 In [8]: show $PATH
2667 2668 A Python string
2668 2669 In [9]: show $$PATH
2669 2670 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2670 2671
2671 2672 You can use the alias facility to acess all of $PATH. See the %rehash
2672 2673 and %rehashx functions, which automatically create aliases for the
2673 2674 contents of your $PATH.
2674 2675
2675 2676 If called with no parameters, %alias prints the current alias table."""
2676 2677
2677 2678 par = parameter_s.strip()
2678 2679 if not par:
2679 2680 stored = self.db.get('stored_aliases', {} )
2680 2681 aliases = sorted(self.shell.alias_manager.aliases)
2681 2682 # for k, v in stored:
2682 2683 # atab.append(k, v[0])
2683 2684
2684 2685 print "Total number of aliases:", len(aliases)
2685 2686 return aliases
2686 2687
2687 2688 # Now try to define a new one
2688 2689 try:
2689 2690 alias,cmd = par.split(None, 1)
2690 2691 except:
2691 2692 print oinspect.getdoc(self.magic_alias)
2692 2693 else:
2693 2694 self.shell.alias_manager.soft_define_alias(alias, cmd)
2694 2695 # end magic_alias
2695 2696
2696 2697 def magic_unalias(self, parameter_s = ''):
2697 2698 """Remove an alias"""
2698 2699
2699 2700 aname = parameter_s.strip()
2700 2701 self.shell.alias_manager.undefine_alias(aname)
2701 2702 stored = self.db.get('stored_aliases', {} )
2702 2703 if aname in stored:
2703 2704 print "Removing %stored alias",aname
2704 2705 del stored[aname]
2705 2706 self.db['stored_aliases'] = stored
2706 2707
2707 2708
2708 2709 def magic_rehashx(self, parameter_s = ''):
2709 2710 """Update the alias table with all executable files in $PATH.
2710 2711
2711 2712 This version explicitly checks that every entry in $PATH is a file
2712 2713 with execute access (os.X_OK), so it is much slower than %rehash.
2713 2714
2714 2715 Under Windows, it checks executability as a match agains a
2715 2716 '|'-separated string of extensions, stored in the IPython config
2716 2717 variable win_exec_ext. This defaults to 'exe|com|bat'.
2717 2718
2718 2719 This function also resets the root module cache of module completer,
2719 2720 used on slow filesystems.
2720 2721 """
2721 2722 from IPython.core.alias import InvalidAliasError
2722 2723
2723 2724 # for the benefit of module completer in ipy_completers.py
2724 2725 del self.db['rootmodules']
2725 2726
2726 2727 path = [os.path.abspath(os.path.expanduser(p)) for p in
2727 2728 os.environ.get('PATH','').split(os.pathsep)]
2728 2729 path = filter(os.path.isdir,path)
2729 2730
2730 2731 syscmdlist = []
2731 2732 # Now define isexec in a cross platform manner.
2732 2733 if os.name == 'posix':
2733 2734 isexec = lambda fname:os.path.isfile(fname) and \
2734 2735 os.access(fname,os.X_OK)
2735 2736 else:
2736 2737 try:
2737 2738 winext = os.environ['pathext'].replace(';','|').replace('.','')
2738 2739 except KeyError:
2739 2740 winext = 'exe|com|bat|py'
2740 2741 if 'py' not in winext:
2741 2742 winext += '|py'
2742 2743 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2743 2744 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2744 2745 savedir = os.getcwd()
2745 2746
2746 2747 # Now walk the paths looking for executables to alias.
2747 2748 try:
2748 2749 # write the whole loop for posix/Windows so we don't have an if in
2749 2750 # the innermost part
2750 2751 if os.name == 'posix':
2751 2752 for pdir in path:
2752 2753 os.chdir(pdir)
2753 2754 for ff in os.listdir(pdir):
2754 2755 if isexec(ff):
2755 2756 try:
2756 2757 # Removes dots from the name since ipython
2757 2758 # will assume names with dots to be python.
2758 2759 self.shell.alias_manager.define_alias(
2759 2760 ff.replace('.',''), ff)
2760 2761 except InvalidAliasError:
2761 2762 pass
2762 2763 else:
2763 2764 syscmdlist.append(ff)
2764 2765 else:
2765 2766 no_alias = self.shell.alias_manager.no_alias
2766 2767 for pdir in path:
2767 2768 os.chdir(pdir)
2768 2769 for ff in os.listdir(pdir):
2769 2770 base, ext = os.path.splitext(ff)
2770 2771 if isexec(ff) and base.lower() not in no_alias:
2771 2772 if ext.lower() == '.exe':
2772 2773 ff = base
2773 2774 try:
2774 2775 # Removes dots from the name since ipython
2775 2776 # will assume names with dots to be python.
2776 2777 self.shell.alias_manager.define_alias(
2777 2778 base.lower().replace('.',''), ff)
2778 2779 except InvalidAliasError:
2779 2780 pass
2780 2781 syscmdlist.append(ff)
2781 2782 db = self.db
2782 2783 db['syscmdlist'] = syscmdlist
2783 2784 finally:
2784 2785 os.chdir(savedir)
2785 2786
2786 2787 def magic_pwd(self, parameter_s = ''):
2787 2788 """Return the current working directory path."""
2788 2789 return os.getcwd()
2789 2790
2790 2791 def magic_cd(self, parameter_s=''):
2791 2792 """Change the current working directory.
2792 2793
2793 2794 This command automatically maintains an internal list of directories
2794 2795 you visit during your IPython session, in the variable _dh. The
2795 2796 command %dhist shows this history nicely formatted. You can also
2796 2797 do 'cd -<tab>' to see directory history conveniently.
2797 2798
2798 2799 Usage:
2799 2800
2800 2801 cd 'dir': changes to directory 'dir'.
2801 2802
2802 2803 cd -: changes to the last visited directory.
2803 2804
2804 2805 cd -<n>: changes to the n-th directory in the directory history.
2805 2806
2806 2807 cd --foo: change to directory that matches 'foo' in history
2807 2808
2808 2809 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
2809 2810 (note: cd <bookmark_name> is enough if there is no
2810 2811 directory <bookmark_name>, but a bookmark with the name exists.)
2811 2812 'cd -b <tab>' allows you to tab-complete bookmark names.
2812 2813
2813 2814 Options:
2814 2815
2815 2816 -q: quiet. Do not print the working directory after the cd command is
2816 2817 executed. By default IPython's cd command does print this directory,
2817 2818 since the default prompts do not display path information.
2818 2819
2819 2820 Note that !cd doesn't work for this purpose because the shell where
2820 2821 !command runs is immediately discarded after executing 'command'."""
2821 2822
2822 2823 parameter_s = parameter_s.strip()
2823 2824 #bkms = self.shell.persist.get("bookmarks",{})
2824 2825
2825 2826 oldcwd = os.getcwd()
2826 2827 numcd = re.match(r'(-)(\d+)$',parameter_s)
2827 2828 # jump in directory history by number
2828 2829 if numcd:
2829 2830 nn = int(numcd.group(2))
2830 2831 try:
2831 2832 ps = self.shell.user_ns['_dh'][nn]
2832 2833 except IndexError:
2833 2834 print 'The requested directory does not exist in history.'
2834 2835 return
2835 2836 else:
2836 2837 opts = {}
2837 2838 elif parameter_s.startswith('--'):
2838 2839 ps = None
2839 2840 fallback = None
2840 2841 pat = parameter_s[2:]
2841 2842 dh = self.shell.user_ns['_dh']
2842 2843 # first search only by basename (last component)
2843 2844 for ent in reversed(dh):
2844 2845 if pat in os.path.basename(ent) and os.path.isdir(ent):
2845 2846 ps = ent
2846 2847 break
2847 2848
2848 2849 if fallback is None and pat in ent and os.path.isdir(ent):
2849 2850 fallback = ent
2850 2851
2851 2852 # if we have no last part match, pick the first full path match
2852 2853 if ps is None:
2853 2854 ps = fallback
2854 2855
2855 2856 if ps is None:
2856 2857 print "No matching entry in directory history"
2857 2858 return
2858 2859 else:
2859 2860 opts = {}
2860 2861
2861 2862
2862 2863 else:
2863 2864 #turn all non-space-escaping backslashes to slashes,
2864 2865 # for c:\windows\directory\names\
2865 2866 parameter_s = re.sub(r'\\(?! )','/', parameter_s)
2866 2867 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
2867 2868 # jump to previous
2868 2869 if ps == '-':
2869 2870 try:
2870 2871 ps = self.shell.user_ns['_dh'][-2]
2871 2872 except IndexError:
2872 2873 raise UsageError('%cd -: No previous directory to change to.')
2873 2874 # jump to bookmark if needed
2874 2875 else:
2875 2876 if not os.path.isdir(ps) or opts.has_key('b'):
2876 2877 bkms = self.db.get('bookmarks', {})
2877 2878
2878 2879 if bkms.has_key(ps):
2879 2880 target = bkms[ps]
2880 2881 print '(bookmark:%s) -> %s' % (ps,target)
2881 2882 ps = target
2882 2883 else:
2883 2884 if opts.has_key('b'):
2884 2885 raise UsageError("Bookmark '%s' not found. "
2885 2886 "Use '%%bookmark -l' to see your bookmarks." % ps)
2886 2887
2887 2888 # at this point ps should point to the target dir
2888 2889 if ps:
2889 2890 try:
2890 2891 os.chdir(os.path.expanduser(ps))
2891 2892 if self.shell.term_title:
2892 2893 set_term_title('IPython: ' + abbrev_cwd())
2893 2894 except OSError:
2894 2895 print sys.exc_info()[1]
2895 2896 else:
2896 2897 cwd = os.getcwd()
2897 2898 dhist = self.shell.user_ns['_dh']
2898 2899 if oldcwd != cwd:
2899 2900 dhist.append(cwd)
2900 2901 self.db['dhist'] = compress_dhist(dhist)[-100:]
2901 2902
2902 2903 else:
2903 2904 os.chdir(self.shell.home_dir)
2904 2905 if self.shell.term_title:
2905 2906 set_term_title('IPython: ' + '~')
2906 2907 cwd = os.getcwd()
2907 2908 dhist = self.shell.user_ns['_dh']
2908 2909
2909 2910 if oldcwd != cwd:
2910 2911 dhist.append(cwd)
2911 2912 self.db['dhist'] = compress_dhist(dhist)[-100:]
2912 2913 if not 'q' in opts and self.shell.user_ns['_dh']:
2913 2914 print self.shell.user_ns['_dh'][-1]
2914 2915
2915 2916
2916 2917 def magic_env(self, parameter_s=''):
2917 2918 """List environment variables."""
2918 2919
2919 2920 return os.environ.data
2920 2921
2921 2922 def magic_pushd(self, parameter_s=''):
2922 2923 """Place the current dir on stack and change directory.
2923 2924
2924 2925 Usage:\\
2925 2926 %pushd ['dirname']
2926 2927 """
2927 2928
2928 2929 dir_s = self.shell.dir_stack
2929 2930 tgt = os.path.expanduser(parameter_s)
2930 2931 cwd = os.getcwd().replace(self.home_dir,'~')
2931 2932 if tgt:
2932 2933 self.magic_cd(parameter_s)
2933 2934 dir_s.insert(0,cwd)
2934 2935 return self.magic_dirs()
2935 2936
2936 2937 def magic_popd(self, parameter_s=''):
2937 2938 """Change to directory popped off the top of the stack.
2938 2939 """
2939 2940 if not self.shell.dir_stack:
2940 2941 raise UsageError("%popd on empty stack")
2941 2942 top = self.shell.dir_stack.pop(0)
2942 2943 self.magic_cd(top)
2943 2944 print "popd ->",top
2944 2945
2945 2946 def magic_dirs(self, parameter_s=''):
2946 2947 """Return the current directory stack."""
2947 2948
2948 2949 return self.shell.dir_stack
2949 2950
2950 2951 def magic_dhist(self, parameter_s=''):
2951 2952 """Print your history of visited directories.
2952 2953
2953 2954 %dhist -> print full history\\
2954 2955 %dhist n -> print last n entries only\\
2955 2956 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
2956 2957
2957 2958 This history is automatically maintained by the %cd command, and
2958 2959 always available as the global list variable _dh. You can use %cd -<n>
2959 2960 to go to directory number <n>.
2960 2961
2961 2962 Note that most of time, you should view directory history by entering
2962 2963 cd -<TAB>.
2963 2964
2964 2965 """
2965 2966
2966 2967 dh = self.shell.user_ns['_dh']
2967 2968 if parameter_s:
2968 2969 try:
2969 2970 args = map(int,parameter_s.split())
2970 2971 except:
2971 2972 self.arg_err(Magic.magic_dhist)
2972 2973 return
2973 2974 if len(args) == 1:
2974 2975 ini,fin = max(len(dh)-(args[0]),0),len(dh)
2975 2976 elif len(args) == 2:
2976 2977 ini,fin = args
2977 2978 else:
2978 2979 self.arg_err(Magic.magic_dhist)
2979 2980 return
2980 2981 else:
2981 2982 ini,fin = 0,len(dh)
2982 2983 nlprint(dh,
2983 2984 header = 'Directory history (kept in _dh)',
2984 2985 start=ini,stop=fin)
2985 2986
2986 2987 @testdec.skip_doctest
2987 2988 def magic_sc(self, parameter_s=''):
2988 2989 """Shell capture - execute a shell command and capture its output.
2989 2990
2990 2991 DEPRECATED. Suboptimal, retained for backwards compatibility.
2991 2992
2992 2993 You should use the form 'var = !command' instead. Example:
2993 2994
2994 2995 "%sc -l myfiles = ls ~" should now be written as
2995 2996
2996 2997 "myfiles = !ls ~"
2997 2998
2998 2999 myfiles.s, myfiles.l and myfiles.n still apply as documented
2999 3000 below.
3000 3001
3001 3002 --
3002 3003 %sc [options] varname=command
3003 3004
3004 3005 IPython will run the given command using commands.getoutput(), and
3005 3006 will then update the user's interactive namespace with a variable
3006 3007 called varname, containing the value of the call. Your command can
3007 3008 contain shell wildcards, pipes, etc.
3008 3009
3009 3010 The '=' sign in the syntax is mandatory, and the variable name you
3010 3011 supply must follow Python's standard conventions for valid names.
3011 3012
3012 3013 (A special format without variable name exists for internal use)
3013 3014
3014 3015 Options:
3015 3016
3016 3017 -l: list output. Split the output on newlines into a list before
3017 3018 assigning it to the given variable. By default the output is stored
3018 3019 as a single string.
3019 3020
3020 3021 -v: verbose. Print the contents of the variable.
3021 3022
3022 3023 In most cases you should not need to split as a list, because the
3023 3024 returned value is a special type of string which can automatically
3024 3025 provide its contents either as a list (split on newlines) or as a
3025 3026 space-separated string. These are convenient, respectively, either
3026 3027 for sequential processing or to be passed to a shell command.
3027 3028
3028 3029 For example:
3029 3030
3030 3031 # all-random
3031 3032
3032 3033 # Capture into variable a
3033 3034 In [1]: sc a=ls *py
3034 3035
3035 3036 # a is a string with embedded newlines
3036 3037 In [2]: a
3037 3038 Out[2]: 'setup.py\\nwin32_manual_post_install.py'
3038 3039
3039 3040 # which can be seen as a list:
3040 3041 In [3]: a.l
3041 3042 Out[3]: ['setup.py', 'win32_manual_post_install.py']
3042 3043
3043 3044 # or as a whitespace-separated string:
3044 3045 In [4]: a.s
3045 3046 Out[4]: 'setup.py win32_manual_post_install.py'
3046 3047
3047 3048 # a.s is useful to pass as a single command line:
3048 3049 In [5]: !wc -l $a.s
3049 3050 146 setup.py
3050 3051 130 win32_manual_post_install.py
3051 3052 276 total
3052 3053
3053 3054 # while the list form is useful to loop over:
3054 3055 In [6]: for f in a.l:
3055 3056 ...: !wc -l $f
3056 3057 ...:
3057 3058 146 setup.py
3058 3059 130 win32_manual_post_install.py
3059 3060
3060 3061 Similiarly, the lists returned by the -l option are also special, in
3061 3062 the sense that you can equally invoke the .s attribute on them to
3062 3063 automatically get a whitespace-separated string from their contents:
3063 3064
3064 3065 In [7]: sc -l b=ls *py
3065 3066
3066 3067 In [8]: b
3067 3068 Out[8]: ['setup.py', 'win32_manual_post_install.py']
3068 3069
3069 3070 In [9]: b.s
3070 3071 Out[9]: 'setup.py win32_manual_post_install.py'
3071 3072
3072 3073 In summary, both the lists and strings used for ouptut capture have
3073 3074 the following special attributes:
3074 3075
3075 3076 .l (or .list) : value as list.
3076 3077 .n (or .nlstr): value as newline-separated string.
3077 3078 .s (or .spstr): value as space-separated string.
3078 3079 """
3079 3080
3080 3081 opts,args = self.parse_options(parameter_s,'lv')
3081 3082 # Try to get a variable name and command to run
3082 3083 try:
3083 3084 # the variable name must be obtained from the parse_options
3084 3085 # output, which uses shlex.split to strip options out.
3085 3086 var,_ = args.split('=',1)
3086 3087 var = var.strip()
3087 3088 # But the the command has to be extracted from the original input
3088 3089 # parameter_s, not on what parse_options returns, to avoid the
3089 3090 # quote stripping which shlex.split performs on it.
3090 3091 _,cmd = parameter_s.split('=',1)
3091 3092 except ValueError:
3092 3093 var,cmd = '',''
3093 3094 # If all looks ok, proceed
3094 3095 out,err = self.shell.getoutputerror(cmd)
3095 3096 if err:
3096 print >> Term.cerr,err
3097 print >> IPython.utils.io.Term.cerr, err
3097 3098 if opts.has_key('l'):
3098 3099 out = SList(out.split('\n'))
3099 3100 else:
3100 3101 out = LSString(out)
3101 3102 if opts.has_key('v'):
3102 3103 print '%s ==\n%s' % (var,pformat(out))
3103 3104 if var:
3104 3105 self.shell.user_ns.update({var:out})
3105 3106 else:
3106 3107 return out
3107 3108
3108 3109 def magic_sx(self, parameter_s=''):
3109 3110 """Shell execute - run a shell command and capture its output.
3110 3111
3111 3112 %sx command
3112 3113
3113 3114 IPython will run the given command using commands.getoutput(), and
3114 3115 return the result formatted as a list (split on '\\n'). Since the
3115 3116 output is _returned_, it will be stored in ipython's regular output
3116 3117 cache Out[N] and in the '_N' automatic variables.
3117 3118
3118 3119 Notes:
3119 3120
3120 3121 1) If an input line begins with '!!', then %sx is automatically
3121 3122 invoked. That is, while:
3122 3123 !ls
3123 3124 causes ipython to simply issue system('ls'), typing
3124 3125 !!ls
3125 3126 is a shorthand equivalent to:
3126 3127 %sx ls
3127 3128
3128 3129 2) %sx differs from %sc in that %sx automatically splits into a list,
3129 3130 like '%sc -l'. The reason for this is to make it as easy as possible
3130 3131 to process line-oriented shell output via further python commands.
3131 3132 %sc is meant to provide much finer control, but requires more
3132 3133 typing.
3133 3134
3134 3135 3) Just like %sc -l, this is a list with special attributes:
3135 3136
3136 3137 .l (or .list) : value as list.
3137 3138 .n (or .nlstr): value as newline-separated string.
3138 3139 .s (or .spstr): value as whitespace-separated string.
3139 3140
3140 3141 This is very useful when trying to use such lists as arguments to
3141 3142 system commands."""
3142 3143
3143 3144 if parameter_s:
3144 3145 out,err = self.shell.getoutputerror(parameter_s)
3145 3146 if err:
3146 print >> Term.cerr,err
3147 print >> IPython.utils.io.Term.cerr, err
3147 3148 return SList(out.split('\n'))
3148 3149
3149 3150 def magic_r(self, parameter_s=''):
3150 3151 """Repeat previous input.
3151 3152
3152 3153 Note: Consider using the more powerfull %rep instead!
3153 3154
3154 3155 If given an argument, repeats the previous command which starts with
3155 3156 the same string, otherwise it just repeats the previous input.
3156 3157
3157 3158 Shell escaped commands (with ! as first character) are not recognized
3158 3159 by this system, only pure python code and magic commands.
3159 3160 """
3160 3161
3161 3162 start = parameter_s.strip()
3162 3163 esc_magic = ESC_MAGIC
3163 3164 # Identify magic commands even if automagic is on (which means
3164 3165 # the in-memory version is different from that typed by the user).
3165 3166 if self.shell.automagic:
3166 3167 start_magic = esc_magic+start
3167 3168 else:
3168 3169 start_magic = start
3169 3170 # Look through the input history in reverse
3170 3171 for n in range(len(self.shell.input_hist)-2,0,-1):
3171 3172 input = self.shell.input_hist[n]
3172 3173 # skip plain 'r' lines so we don't recurse to infinity
3173 3174 if input != '_ip.magic("r")\n' and \
3174 3175 (input.startswith(start) or input.startswith(start_magic)):
3175 3176 #print 'match',`input` # dbg
3176 3177 print 'Executing:',input,
3177 3178 self.shell.runlines(input)
3178 3179 return
3179 3180 print 'No previous input matching `%s` found.' % start
3180 3181
3181 3182
3182 3183 def magic_bookmark(self, parameter_s=''):
3183 3184 """Manage IPython's bookmark system.
3184 3185
3185 3186 %bookmark <name> - set bookmark to current dir
3186 3187 %bookmark <name> <dir> - set bookmark to <dir>
3187 3188 %bookmark -l - list all bookmarks
3188 3189 %bookmark -d <name> - remove bookmark
3189 3190 %bookmark -r - remove all bookmarks
3190 3191
3191 3192 You can later on access a bookmarked folder with:
3192 3193 %cd -b <name>
3193 3194 or simply '%cd <name>' if there is no directory called <name> AND
3194 3195 there is such a bookmark defined.
3195 3196
3196 3197 Your bookmarks persist through IPython sessions, but they are
3197 3198 associated with each profile."""
3198 3199
3199 3200 opts,args = self.parse_options(parameter_s,'drl',mode='list')
3200 3201 if len(args) > 2:
3201 3202 raise UsageError("%bookmark: too many arguments")
3202 3203
3203 3204 bkms = self.db.get('bookmarks',{})
3204 3205
3205 3206 if opts.has_key('d'):
3206 3207 try:
3207 3208 todel = args[0]
3208 3209 except IndexError:
3209 3210 raise UsageError(
3210 3211 "%bookmark -d: must provide a bookmark to delete")
3211 3212 else:
3212 3213 try:
3213 3214 del bkms[todel]
3214 3215 except KeyError:
3215 3216 raise UsageError(
3216 3217 "%%bookmark -d: Can't delete bookmark '%s'" % todel)
3217 3218
3218 3219 elif opts.has_key('r'):
3219 3220 bkms = {}
3220 3221 elif opts.has_key('l'):
3221 3222 bks = bkms.keys()
3222 3223 bks.sort()
3223 3224 if bks:
3224 3225 size = max(map(len,bks))
3225 3226 else:
3226 3227 size = 0
3227 3228 fmt = '%-'+str(size)+'s -> %s'
3228 3229 print 'Current bookmarks:'
3229 3230 for bk in bks:
3230 3231 print fmt % (bk,bkms[bk])
3231 3232 else:
3232 3233 if not args:
3233 3234 raise UsageError("%bookmark: You must specify the bookmark name")
3234 3235 elif len(args)==1:
3235 3236 bkms[args[0]] = os.getcwd()
3236 3237 elif len(args)==2:
3237 3238 bkms[args[0]] = args[1]
3238 3239 self.db['bookmarks'] = bkms
3239 3240
3240 3241 def magic_pycat(self, parameter_s=''):
3241 3242 """Show a syntax-highlighted file through a pager.
3242 3243
3243 3244 This magic is similar to the cat utility, but it will assume the file
3244 3245 to be Python source and will show it with syntax highlighting. """
3245 3246
3246 3247 try:
3247 3248 filename = get_py_filename(parameter_s)
3248 3249 cont = file_read(filename)
3249 3250 except IOError:
3250 3251 try:
3251 3252 cont = eval(parameter_s,self.user_ns)
3252 3253 except NameError:
3253 3254 cont = None
3254 3255 if cont is None:
3255 3256 print "Error: no such file or variable"
3256 3257 return
3257 3258
3258 3259 page(self.shell.pycolorize(cont),
3259 3260 screen_lines=self.shell.usable_screen_length)
3260 3261
3261 3262 def _rerun_pasted(self):
3262 3263 """ Rerun a previously pasted command.
3263 3264 """
3264 3265 b = self.user_ns.get('pasted_block', None)
3265 3266 if b is None:
3266 3267 raise UsageError('No previous pasted block available')
3267 3268 print "Re-executing '%s...' (%d chars)"% (b.split('\n',1)[0], len(b))
3268 3269 exec b in self.user_ns
3269 3270
3270 3271 def _get_pasted_lines(self, sentinel):
3271 3272 """ Yield pasted lines until the user enters the given sentinel value.
3272 3273 """
3273 3274 from IPython.core import interactiveshell
3274 3275 print "Pasting code; enter '%s' alone on the line to stop." % sentinel
3275 3276 while True:
3276 3277 l = interactiveshell.raw_input_original(':')
3277 3278 if l == sentinel:
3278 3279 return
3279 3280 else:
3280 3281 yield l
3281 3282
3282 3283 def _strip_pasted_lines_for_code(self, raw_lines):
3283 3284 """ Strip non-code parts of a sequence of lines to return a block of
3284 3285 code.
3285 3286 """
3286 3287 # Regular expressions that declare text we strip from the input:
3287 3288 strip_re = [r'^\s*In \[\d+\]:', # IPython input prompt
3288 3289 r'^\s*(\s?>)+', # Python input prompt
3289 3290 r'^\s*\.{3,}', # Continuation prompts
3290 3291 r'^\++',
3291 3292 ]
3292 3293
3293 3294 strip_from_start = map(re.compile,strip_re)
3294 3295
3295 3296 lines = []
3296 3297 for l in raw_lines:
3297 3298 for pat in strip_from_start:
3298 3299 l = pat.sub('',l)
3299 3300 lines.append(l)
3300 3301
3301 3302 block = "\n".join(lines) + '\n'
3302 3303 #print "block:\n",block
3303 3304 return block
3304 3305
3305 3306 def _execute_block(self, block, par):
3306 3307 """ Execute a block, or store it in a variable, per the user's request.
3307 3308 """
3308 3309 if not par:
3309 3310 b = textwrap.dedent(block)
3310 3311 self.user_ns['pasted_block'] = b
3311 3312 exec b in self.user_ns
3312 3313 else:
3313 3314 self.user_ns[par] = SList(block.splitlines())
3314 3315 print "Block assigned to '%s'" % par
3315 3316
3316 3317 def magic_cpaste(self, parameter_s=''):
3317 3318 """Allows you to paste & execute a pre-formatted code block from clipboard.
3318 3319
3319 3320 You must terminate the block with '--' (two minus-signs) alone on the
3320 3321 line. You can also provide your own sentinel with '%paste -s %%' ('%%'
3321 3322 is the new sentinel for this operation)
3322 3323
3323 3324 The block is dedented prior to execution to enable execution of method
3324 3325 definitions. '>' and '+' characters at the beginning of a line are
3325 3326 ignored, to allow pasting directly from e-mails, diff files and
3326 3327 doctests (the '...' continuation prompt is also stripped). The
3327 3328 executed block is also assigned to variable named 'pasted_block' for
3328 3329 later editing with '%edit pasted_block'.
3329 3330
3330 3331 You can also pass a variable name as an argument, e.g. '%cpaste foo'.
3331 3332 This assigns the pasted block to variable 'foo' as string, without
3332 3333 dedenting or executing it (preceding >>> and + is still stripped)
3333 3334
3334 3335 '%cpaste -r' re-executes the block previously entered by cpaste.
3335 3336
3336 3337 Do not be alarmed by garbled output on Windows (it's a readline bug).
3337 3338 Just press enter and type -- (and press enter again) and the block
3338 3339 will be what was just pasted.
3339 3340
3340 3341 IPython statements (magics, shell escapes) are not supported (yet).
3341 3342
3342 3343 See also
3343 3344 --------
3344 3345 paste: automatically pull code from clipboard.
3345 3346 """
3346 3347
3347 3348 opts,args = self.parse_options(parameter_s,'rs:',mode='string')
3348 3349 par = args.strip()
3349 3350 if opts.has_key('r'):
3350 3351 self._rerun_pasted()
3351 3352 return
3352 3353
3353 3354 sentinel = opts.get('s','--')
3354 3355
3355 3356 block = self._strip_pasted_lines_for_code(
3356 3357 self._get_pasted_lines(sentinel))
3357 3358
3358 3359 self._execute_block(block, par)
3359 3360
3360 3361 def magic_paste(self, parameter_s=''):
3361 3362 """Allows you to paste & execute a pre-formatted code block from clipboard.
3362 3363
3363 3364 The text is pulled directly from the clipboard without user
3364 3365 intervention and printed back on the screen before execution (unless
3365 3366 the -q flag is given to force quiet mode).
3366 3367
3367 3368 The block is dedented prior to execution to enable execution of method
3368 3369 definitions. '>' and '+' characters at the beginning of a line are
3369 3370 ignored, to allow pasting directly from e-mails, diff files and
3370 3371 doctests (the '...' continuation prompt is also stripped). The
3371 3372 executed block is also assigned to variable named 'pasted_block' for
3372 3373 later editing with '%edit pasted_block'.
3373 3374
3374 3375 You can also pass a variable name as an argument, e.g. '%paste foo'.
3375 3376 This assigns the pasted block to variable 'foo' as string, without
3376 3377 dedenting or executing it (preceding >>> and + is still stripped)
3377 3378
3378 3379 Options
3379 3380 -------
3380 3381
3381 3382 -r: re-executes the block previously entered by cpaste.
3382 3383
3383 3384 -q: quiet mode: do not echo the pasted text back to the terminal.
3384 3385
3385 3386 IPython statements (magics, shell escapes) are not supported (yet).
3386 3387
3387 3388 See also
3388 3389 --------
3389 3390 cpaste: manually paste code into terminal until you mark its end.
3390 3391 """
3391 3392 opts,args = self.parse_options(parameter_s,'rq',mode='string')
3392 3393 par = args.strip()
3393 3394 if opts.has_key('r'):
3394 3395 self._rerun_pasted()
3395 3396 return
3396 3397
3397 3398 text = self.shell.hooks.clipboard_get()
3398 3399 block = self._strip_pasted_lines_for_code(text.splitlines())
3399 3400
3400 3401 # By default, echo back to terminal unless quiet mode is requested
3401 3402 if not opts.has_key('q'):
3402 3403 write = self.shell.write
3403 3404 write(self.shell.pycolorize(block))
3404 3405 if not block.endswith('\n'):
3405 3406 write('\n')
3406 3407 write("## -- End pasted text --\n")
3407 3408
3408 3409 self._execute_block(block, par)
3409 3410
3410 3411 def magic_quickref(self,arg):
3411 3412 """ Show a quick reference sheet """
3412 3413 import IPython.core.usage
3413 3414 qr = IPython.core.usage.quick_reference + self.magic_magic('-brief')
3414 3415
3415 3416 page(qr)
3416 3417
3417 3418 def magic_doctest_mode(self,parameter_s=''):
3418 3419 """Toggle doctest mode on and off.
3419 3420
3420 3421 This mode allows you to toggle the prompt behavior between normal
3421 3422 IPython prompts and ones that are as similar to the default IPython
3422 3423 interpreter as possible.
3423 3424
3424 3425 It also supports the pasting of code snippets that have leading '>>>'
3425 3426 and '...' prompts in them. This means that you can paste doctests from
3426 3427 files or docstrings (even if they have leading whitespace), and the
3427 3428 code will execute correctly. You can then use '%history -tn' to see
3428 3429 the translated history without line numbers; this will give you the
3429 3430 input after removal of all the leading prompts and whitespace, which
3430 3431 can be pasted back into an editor.
3431 3432
3432 3433 With these features, you can switch into this mode easily whenever you
3433 3434 need to do testing and changes to doctests, without having to leave
3434 3435 your existing IPython session.
3435 3436 """
3436 3437
3437 3438 from IPython.utils.ipstruct import Struct
3438 3439
3439 3440 # Shorthands
3440 3441 shell = self.shell
3441 3442 oc = shell.outputcache
3442 3443 meta = shell.meta
3443 3444 # dstore is a data store kept in the instance metadata bag to track any
3444 3445 # changes we make, so we can undo them later.
3445 3446 dstore = meta.setdefault('doctest_mode',Struct())
3446 3447 save_dstore = dstore.setdefault
3447 3448
3448 3449 # save a few values we'll need to recover later
3449 3450 mode = save_dstore('mode',False)
3450 3451 save_dstore('rc_pprint',shell.pprint)
3451 3452 save_dstore('xmode',shell.InteractiveTB.mode)
3452 3453 save_dstore('rc_separate_out',shell.separate_out)
3453 3454 save_dstore('rc_separate_out2',shell.separate_out2)
3454 3455 save_dstore('rc_prompts_pad_left',shell.prompts_pad_left)
3455 3456 save_dstore('rc_separate_in',shell.separate_in)
3456 3457
3457 3458 if mode == False:
3458 3459 # turn on
3459 3460 oc.prompt1.p_template = '>>> '
3460 3461 oc.prompt2.p_template = '... '
3461 3462 oc.prompt_out.p_template = ''
3462 3463
3463 3464 # Prompt separators like plain python
3464 3465 oc.input_sep = oc.prompt1.sep = ''
3465 3466 oc.output_sep = ''
3466 3467 oc.output_sep2 = ''
3467 3468
3468 3469 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3469 3470 oc.prompt_out.pad_left = False
3470 3471
3471 3472 shell.pprint = False
3472 3473
3473 3474 shell.magic_xmode('Plain')
3474 3475
3475 3476 else:
3476 3477 # turn off
3477 3478 oc.prompt1.p_template = shell.prompt_in1
3478 3479 oc.prompt2.p_template = shell.prompt_in2
3479 3480 oc.prompt_out.p_template = shell.prompt_out
3480 3481
3481 3482 oc.input_sep = oc.prompt1.sep = dstore.rc_separate_in
3482 3483
3483 3484 oc.output_sep = dstore.rc_separate_out
3484 3485 oc.output_sep2 = dstore.rc_separate_out2
3485 3486
3486 3487 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3487 3488 oc.prompt_out.pad_left = dstore.rc_prompts_pad_left
3488 3489
3489 3490 shell.pprint = dstore.rc_pprint
3490 3491
3491 3492 shell.magic_xmode(dstore.xmode)
3492 3493
3493 3494 # Store new mode and inform
3494 3495 dstore.mode = bool(1-int(mode))
3495 3496 print 'Doctest mode is:',
3496 3497 print ['OFF','ON'][dstore.mode]
3497 3498
3498 3499 def magic_gui(self, parameter_s=''):
3499 3500 """Enable or disable IPython GUI event loop integration.
3500 3501
3501 3502 %gui [-a] [GUINAME]
3502 3503
3503 3504 This magic replaces IPython's threaded shells that were activated
3504 3505 using the (pylab/wthread/etc.) command line flags. GUI toolkits
3505 3506 can now be enabled, disabled and swtiched at runtime and keyboard
3506 3507 interrupts should work without any problems. The following toolkits
3507 3508 are supported: wxPython, PyQt4, PyGTK, and Tk::
3508 3509
3509 3510 %gui wx # enable wxPython event loop integration
3510 3511 %gui qt4|qt # enable PyQt4 event loop integration
3511 3512 %gui gtk # enable PyGTK event loop integration
3512 3513 %gui tk # enable Tk event loop integration
3513 3514 %gui # disable all event loop integration
3514 3515
3515 3516 WARNING: after any of these has been called you can simply create
3516 3517 an application object, but DO NOT start the event loop yourself, as
3517 3518 we have already handled that.
3518 3519
3519 3520 If you want us to create an appropriate application object add the
3520 3521 "-a" flag to your command::
3521 3522
3522 3523 %gui -a wx
3523 3524
3524 3525 This is highly recommended for most users.
3525 3526 """
3526 3527 opts, arg = self.parse_options(parameter_s,'a')
3527 3528 if arg=='': arg = None
3528 3529 return enable_gui(arg, 'a' in opts)
3529 3530
3530 3531 def magic_load_ext(self, module_str):
3531 3532 """Load an IPython extension by its module name."""
3532 3533 return self.extension_manager.load_extension(module_str)
3533 3534
3534 3535 def magic_unload_ext(self, module_str):
3535 3536 """Unload an IPython extension by its module name."""
3536 3537 self.extension_manager.unload_extension(module_str)
3537 3538
3538 3539 def magic_reload_ext(self, module_str):
3539 3540 """Reload an IPython extension by its module name."""
3540 3541 self.extension_manager.reload_extension(module_str)
3541 3542
3542 3543 @testdec.skip_doctest
3543 3544 def magic_install_profiles(self, s):
3544 3545 """Install the default IPython profiles into the .ipython dir.
3545 3546
3546 3547 If the default profiles have already been installed, they will not
3547 3548 be overwritten. You can force overwriting them by using the ``-o``
3548 3549 option::
3549 3550
3550 3551 In [1]: %install_profiles -o
3551 3552 """
3552 3553 if '-o' in s:
3553 3554 overwrite = True
3554 3555 else:
3555 3556 overwrite = False
3556 3557 from IPython.config import profile
3557 3558 profile_dir = os.path.split(profile.__file__)[0]
3558 3559 ipython_dir = self.ipython_dir
3559 3560 files = os.listdir(profile_dir)
3560 3561
3561 3562 to_install = []
3562 3563 for f in files:
3563 3564 if f.startswith('ipython_config'):
3564 3565 src = os.path.join(profile_dir, f)
3565 3566 dst = os.path.join(ipython_dir, f)
3566 3567 if (not os.path.isfile(dst)) or overwrite:
3567 3568 to_install.append((f, src, dst))
3568 3569 if len(to_install)>0:
3569 3570 print "Installing profiles to: ", ipython_dir
3570 3571 for (f, src, dst) in to_install:
3571 3572 shutil.copy(src, dst)
3572 3573 print " %s" % f
3573 3574
3574 3575 def magic_install_default_config(self, s):
3575 3576 """Install IPython's default config file into the .ipython dir.
3576 3577
3577 3578 If the default config file (:file:`ipython_config.py`) is already
3578 3579 installed, it will not be overwritten. You can force overwriting
3579 3580 by using the ``-o`` option::
3580 3581
3581 3582 In [1]: %install_default_config
3582 3583 """
3583 3584 if '-o' in s:
3584 3585 overwrite = True
3585 3586 else:
3586 3587 overwrite = False
3587 3588 from IPython.config import default
3588 3589 config_dir = os.path.split(default.__file__)[0]
3589 3590 ipython_dir = self.ipython_dir
3590 3591 default_config_file_name = 'ipython_config.py'
3591 3592 src = os.path.join(config_dir, default_config_file_name)
3592 3593 dst = os.path.join(ipython_dir, default_config_file_name)
3593 3594 if (not os.path.isfile(dst)) or overwrite:
3594 3595 shutil.copy(src, dst)
3595 3596 print "Installing default config file: %s" % dst
3596 3597
3597 3598 # Pylab support: simple wrappers that activate pylab, load gui input
3598 3599 # handling and modify slightly %run
3599 3600
3600 3601 @testdec.skip_doctest
3601 3602 def _pylab_magic_run(self, parameter_s=''):
3602 3603 Magic.magic_run(self, parameter_s,
3603 3604 runner=mpl_runner(self.shell.safe_execfile))
3604 3605
3605 3606 _pylab_magic_run.__doc__ = magic_run.__doc__
3606 3607
3607 3608 @testdec.skip_doctest
3608 3609 def magic_pylab(self, s):
3609 3610 """Load numpy and matplotlib to work interactively.
3610 3611
3611 3612 %pylab [GUINAME]
3612 3613
3613 3614 This function lets you activate pylab (matplotlib, numpy and
3614 3615 interactive support) at any point during an IPython session.
3615 3616
3616 3617 It will import at the top level numpy as np, pyplot as plt, matplotlib,
3617 3618 pylab and mlab, as well as all names from numpy and pylab.
3618 3619
3619 3620 Parameters
3620 3621 ----------
3621 3622 guiname : optional
3622 3623 One of the valid arguments to the %gui magic ('qt', 'wx', 'gtk' or
3623 3624 'tk'). If given, the corresponding Matplotlib backend is used,
3624 3625 otherwise matplotlib's default (which you can override in your
3625 3626 matplotlib config file) is used.
3626 3627
3627 3628 Examples
3628 3629 --------
3629 3630 In this case, where the MPL default is TkAgg:
3630 3631 In [2]: %pylab
3631 3632
3632 3633 Welcome to pylab, a matplotlib-based Python environment.
3633 3634 Backend in use: TkAgg
3634 3635 For more information, type 'help(pylab)'.
3635 3636
3636 3637 But you can explicitly request a different backend:
3637 3638 In [3]: %pylab qt
3638 3639
3639 3640 Welcome to pylab, a matplotlib-based Python environment.
3640 3641 Backend in use: Qt4Agg
3641 3642 For more information, type 'help(pylab)'.
3642 3643 """
3643 3644 self.shell.enable_pylab(s)
3644 3645
3645 3646 def magic_tb(self, s):
3646 3647 """Print the last traceback with the currently active exception mode.
3647 3648
3648 3649 See %xmode for changing exception reporting modes."""
3649 3650 self.shell.showtraceback()
3650 3651
3651 3652 # end Magic
@@ -1,609 +1,609 b''
1 1 # -*- coding: utf-8 -*-
2 2 """Tools for inspecting Python objects.
3 3
4 4 Uses syntax highlighting for presenting the various information elements.
5 5
6 6 Similar in spirit to the inspect module, but all calls take a name argument to
7 7 reference the name under which an object is being read.
8 8 """
9 9
10 10 #*****************************************************************************
11 11 # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu>
12 12 #
13 13 # Distributed under the terms of the BSD License. The full license is in
14 14 # the file COPYING, distributed as part of this software.
15 15 #*****************************************************************************
16 16
17 17 __all__ = ['Inspector','InspectColors']
18 18
19 19 # stdlib modules
20 20 import __builtin__
21 21 import StringIO
22 22 import inspect
23 23 import linecache
24 24 import os
25 25 import string
26 26 import sys
27 27 import types
28 28
29 29 # IPython's own
30 30 from IPython.core.page import page
31 31 from IPython.external.Itpl import itpl
32 32 from IPython.utils import PyColorize
33 from IPython.utils.io import Term
33 import IPython.utils.io
34 34 from IPython.utils.text import indent
35 35 from IPython.utils.wildcard import list_namespace
36 36 from IPython.utils.coloransi import *
37 37
38 38 #****************************************************************************
39 39 # HACK!!! This is a crude fix for bugs in python 2.3's inspect module. We
40 40 # simply monkeypatch inspect with code copied from python 2.4.
41 41 if sys.version_info[:2] == (2,3):
42 42 from inspect import ismodule, getabsfile, modulesbyfile
43 43 def getmodule(object):
44 44 """Return the module an object was defined in, or None if not found."""
45 45 if ismodule(object):
46 46 return object
47 47 if hasattr(object, '__module__'):
48 48 return sys.modules.get(object.__module__)
49 49 try:
50 50 file = getabsfile(object)
51 51 except TypeError:
52 52 return None
53 53 if file in modulesbyfile:
54 54 return sys.modules.get(modulesbyfile[file])
55 55 for module in sys.modules.values():
56 56 if hasattr(module, '__file__'):
57 57 modulesbyfile[
58 58 os.path.realpath(
59 59 getabsfile(module))] = module.__name__
60 60 if file in modulesbyfile:
61 61 return sys.modules.get(modulesbyfile[file])
62 62 main = sys.modules['__main__']
63 63 if not hasattr(object, '__name__'):
64 64 return None
65 65 if hasattr(main, object.__name__):
66 66 mainobject = getattr(main, object.__name__)
67 67 if mainobject is object:
68 68 return main
69 69 builtin = sys.modules['__builtin__']
70 70 if hasattr(builtin, object.__name__):
71 71 builtinobject = getattr(builtin, object.__name__)
72 72 if builtinobject is object:
73 73 return builtin
74 74
75 75 inspect.getmodule = getmodule
76 76
77 77 #****************************************************************************
78 78 # Builtin color schemes
79 79
80 80 Colors = TermColors # just a shorthand
81 81
82 82 # Build a few color schemes
83 83 NoColor = ColorScheme(
84 84 'NoColor',{
85 85 'header' : Colors.NoColor,
86 86 'normal' : Colors.NoColor # color off (usu. Colors.Normal)
87 87 } )
88 88
89 89 LinuxColors = ColorScheme(
90 90 'Linux',{
91 91 'header' : Colors.LightRed,
92 92 'normal' : Colors.Normal # color off (usu. Colors.Normal)
93 93 } )
94 94
95 95 LightBGColors = ColorScheme(
96 96 'LightBG',{
97 97 'header' : Colors.Red,
98 98 'normal' : Colors.Normal # color off (usu. Colors.Normal)
99 99 } )
100 100
101 101 # Build table of color schemes (needed by the parser)
102 102 InspectColors = ColorSchemeTable([NoColor,LinuxColors,LightBGColors],
103 103 'Linux')
104 104
105 105 #****************************************************************************
106 106 # Auxiliary functions
107 107 def getdoc(obj):
108 108 """Stable wrapper around inspect.getdoc.
109 109
110 110 This can't crash because of attribute problems.
111 111
112 112 It also attempts to call a getdoc() method on the given object. This
113 113 allows objects which provide their docstrings via non-standard mechanisms
114 114 (like Pyro proxies) to still be inspected by ipython's ? system."""
115 115
116 116 ds = None # default return value
117 117 try:
118 118 ds = inspect.getdoc(obj)
119 119 except:
120 120 # Harden against an inspect failure, which can occur with
121 121 # SWIG-wrapped extensions.
122 122 pass
123 123 # Allow objects to offer customized documentation via a getdoc method:
124 124 try:
125 125 ds2 = obj.getdoc()
126 126 except:
127 127 pass
128 128 else:
129 129 # if we get extra info, we add it to the normal docstring.
130 130 if ds is None:
131 131 ds = ds2
132 132 else:
133 133 ds = '%s\n%s' % (ds,ds2)
134 134 return ds
135 135
136 136
137 137 def getsource(obj,is_binary=False):
138 138 """Wrapper around inspect.getsource.
139 139
140 140 This can be modified by other projects to provide customized source
141 141 extraction.
142 142
143 143 Inputs:
144 144
145 145 - obj: an object whose source code we will attempt to extract.
146 146
147 147 Optional inputs:
148 148
149 149 - is_binary: whether the object is known to come from a binary source.
150 150 This implementation will skip returning any output for binary objects, but
151 151 custom extractors may know how to meaningfully process them."""
152 152
153 153 if is_binary:
154 154 return None
155 155 else:
156 156 try:
157 157 src = inspect.getsource(obj)
158 158 except TypeError:
159 159 if hasattr(obj,'__class__'):
160 160 src = inspect.getsource(obj.__class__)
161 161 return src
162 162
163 163 def getargspec(obj):
164 164 """Get the names and default values of a function's arguments.
165 165
166 166 A tuple of four things is returned: (args, varargs, varkw, defaults).
167 167 'args' is a list of the argument names (it may contain nested lists).
168 168 'varargs' and 'varkw' are the names of the * and ** arguments or None.
169 169 'defaults' is an n-tuple of the default values of the last n arguments.
170 170
171 171 Modified version of inspect.getargspec from the Python Standard
172 172 Library."""
173 173
174 174 if inspect.isfunction(obj):
175 175 func_obj = obj
176 176 elif inspect.ismethod(obj):
177 177 func_obj = obj.im_func
178 178 else:
179 179 raise TypeError, 'arg is not a Python function'
180 180 args, varargs, varkw = inspect.getargs(func_obj.func_code)
181 181 return args, varargs, varkw, func_obj.func_defaults
182 182
183 183 #****************************************************************************
184 184 # Class definitions
185 185
186 186 class myStringIO(StringIO.StringIO):
187 187 """Adds a writeln method to normal StringIO."""
188 188 def writeln(self,*arg,**kw):
189 189 """Does a write() and then a write('\n')"""
190 190 self.write(*arg,**kw)
191 191 self.write('\n')
192 192
193 193
194 194 class Inspector:
195 195 def __init__(self,color_table,code_color_table,scheme,
196 196 str_detail_level=0):
197 197 self.color_table = color_table
198 198 self.parser = PyColorize.Parser(code_color_table,out='str')
199 199 self.format = self.parser.format
200 200 self.str_detail_level = str_detail_level
201 201 self.set_active_scheme(scheme)
202 202
203 203 def __getdef(self,obj,oname=''):
204 204 """Return the definition header for any callable object.
205 205
206 206 If any exception is generated, None is returned instead and the
207 207 exception is suppressed."""
208 208
209 209 try:
210 210 return oname + inspect.formatargspec(*getargspec(obj))
211 211 except:
212 212 return None
213 213
214 214 def __head(self,h):
215 215 """Return a header string with proper colors."""
216 216 return '%s%s%s' % (self.color_table.active_colors.header,h,
217 217 self.color_table.active_colors.normal)
218 218
219 219 def set_active_scheme(self,scheme):
220 220 self.color_table.set_active_scheme(scheme)
221 221 self.parser.color_table.set_active_scheme(scheme)
222 222
223 223 def noinfo(self,msg,oname):
224 224 """Generic message when no information is found."""
225 225 print 'No %s found' % msg,
226 226 if oname:
227 227 print 'for %s' % oname
228 228 else:
229 229 print
230 230
231 231 def pdef(self,obj,oname=''):
232 232 """Print the definition header for any callable object.
233 233
234 234 If the object is a class, print the constructor information."""
235 235
236 236 if not callable(obj):
237 237 print 'Object is not callable.'
238 238 return
239 239
240 240 header = ''
241 241
242 242 if inspect.isclass(obj):
243 243 header = self.__head('Class constructor information:\n')
244 244 obj = obj.__init__
245 245 elif type(obj) is types.InstanceType:
246 246 obj = obj.__call__
247 247
248 248 output = self.__getdef(obj,oname)
249 249 if output is None:
250 250 self.noinfo('definition header',oname)
251 251 else:
252 print >>Term.cout, header,self.format(output),
252 print >>IPython.utils.io.Term.cout, header,self.format(output),
253 253
254 254 def pdoc(self,obj,oname='',formatter = None):
255 255 """Print the docstring for any object.
256 256
257 257 Optional:
258 258 -formatter: a function to run the docstring through for specially
259 259 formatted docstrings."""
260 260
261 261 head = self.__head # so that itpl can find it even if private
262 262 ds = getdoc(obj)
263 263 if formatter:
264 264 ds = formatter(ds)
265 265 if inspect.isclass(obj):
266 266 init_ds = getdoc(obj.__init__)
267 267 output = itpl('$head("Class Docstring:")\n'
268 268 '$indent(ds)\n'
269 269 '$head("Constructor Docstring"):\n'
270 270 '$indent(init_ds)')
271 271 elif (type(obj) is types.InstanceType or isinstance(obj,object)) \
272 272 and hasattr(obj,'__call__'):
273 273 call_ds = getdoc(obj.__call__)
274 274 if call_ds:
275 275 output = itpl('$head("Class Docstring:")\n$indent(ds)\n'
276 276 '$head("Calling Docstring:")\n$indent(call_ds)')
277 277 else:
278 278 output = ds
279 279 else:
280 280 output = ds
281 281 if output is None:
282 282 self.noinfo('documentation',oname)
283 283 return
284 284 page(output)
285 285
286 286 def psource(self,obj,oname=''):
287 287 """Print the source code for an object."""
288 288
289 289 # Flush the source cache because inspect can return out-of-date source
290 290 linecache.checkcache()
291 291 try:
292 292 src = getsource(obj)
293 293 except:
294 294 self.noinfo('source',oname)
295 295 else:
296 296 page(self.format(src))
297 297
298 298 def pfile(self,obj,oname=''):
299 299 """Show the whole file where an object was defined."""
300 300
301 301 try:
302 302 try:
303 303 lineno = inspect.getsourcelines(obj)[1]
304 304 except TypeError:
305 305 # For instances, try the class object like getsource() does
306 306 if hasattr(obj,'__class__'):
307 307 lineno = inspect.getsourcelines(obj.__class__)[1]
308 308 # Adjust the inspected object so getabsfile() below works
309 309 obj = obj.__class__
310 310 except:
311 311 self.noinfo('file',oname)
312 312 return
313 313
314 314 # We only reach this point if object was successfully queried
315 315
316 316 # run contents of file through pager starting at line
317 317 # where the object is defined
318 318 ofile = inspect.getabsfile(obj)
319 319
320 320 if (ofile.endswith('.so') or ofile.endswith('.dll')):
321 321 print 'File %r is binary, not printing.' % ofile
322 322 elif not os.path.isfile(ofile):
323 323 print 'File %r does not exist, not printing.' % ofile
324 324 else:
325 325 # Print only text files, not extension binaries. Note that
326 326 # getsourcelines returns lineno with 1-offset and page() uses
327 327 # 0-offset, so we must adjust.
328 328 page(self.format(open(ofile).read()),lineno-1)
329 329
330 330 def pinfo(self,obj,oname='',formatter=None,info=None,detail_level=0):
331 331 """Show detailed information about an object.
332 332
333 333 Optional arguments:
334 334
335 335 - oname: name of the variable pointing to the object.
336 336
337 337 - formatter: special formatter for docstrings (see pdoc)
338 338
339 339 - info: a structure with some information fields which may have been
340 340 precomputed already.
341 341
342 342 - detail_level: if set to 1, more information is given.
343 343 """
344 344
345 345 obj_type = type(obj)
346 346
347 347 header = self.__head
348 348 if info is None:
349 349 ismagic = 0
350 350 isalias = 0
351 351 ospace = ''
352 352 else:
353 353 ismagic = info.ismagic
354 354 isalias = info.isalias
355 355 ospace = info.namespace
356 356 # Get docstring, special-casing aliases:
357 357 if isalias:
358 358 if not callable(obj):
359 359 try:
360 360 ds = "Alias to the system command:\n %s" % obj[1]
361 361 except:
362 362 ds = "Alias: " + str(obj)
363 363 else:
364 364 ds = "Alias to " + str(obj)
365 365 if obj.__doc__:
366 366 ds += "\nDocstring:\n" + obj.__doc__
367 367 else:
368 368 ds = getdoc(obj)
369 369 if ds is None:
370 370 ds = '<no docstring>'
371 371 if formatter is not None:
372 372 ds = formatter(ds)
373 373
374 374 # store output in a list which gets joined with \n at the end.
375 375 out = myStringIO()
376 376
377 377 string_max = 200 # max size of strings to show (snipped if longer)
378 378 shalf = int((string_max -5)/2)
379 379
380 380 if ismagic:
381 381 obj_type_name = 'Magic function'
382 382 elif isalias:
383 383 obj_type_name = 'System alias'
384 384 else:
385 385 obj_type_name = obj_type.__name__
386 386 out.writeln(header('Type:\t\t')+obj_type_name)
387 387
388 388 try:
389 389 bclass = obj.__class__
390 390 out.writeln(header('Base Class:\t')+str(bclass))
391 391 except: pass
392 392
393 393 # String form, but snip if too long in ? form (full in ??)
394 394 if detail_level >= self.str_detail_level:
395 395 try:
396 396 ostr = str(obj)
397 397 str_head = 'String Form:'
398 398 if not detail_level and len(ostr)>string_max:
399 399 ostr = ostr[:shalf] + ' <...> ' + ostr[-shalf:]
400 400 ostr = ("\n" + " " * len(str_head.expandtabs())).\
401 401 join(map(string.strip,ostr.split("\n")))
402 402 if ostr.find('\n') > -1:
403 403 # Print multi-line strings starting at the next line.
404 404 str_sep = '\n'
405 405 else:
406 406 str_sep = '\t'
407 407 out.writeln("%s%s%s" % (header(str_head),str_sep,ostr))
408 408 except:
409 409 pass
410 410
411 411 if ospace:
412 412 out.writeln(header('Namespace:\t')+ospace)
413 413
414 414 # Length (for strings and lists)
415 415 try:
416 416 length = str(len(obj))
417 417 out.writeln(header('Length:\t\t')+length)
418 418 except: pass
419 419
420 420 # Filename where object was defined
421 421 binary_file = False
422 422 try:
423 423 try:
424 424 fname = inspect.getabsfile(obj)
425 425 except TypeError:
426 426 # For an instance, the file that matters is where its class was
427 427 # declared.
428 428 if hasattr(obj,'__class__'):
429 429 fname = inspect.getabsfile(obj.__class__)
430 430 if fname.endswith('<string>'):
431 431 fname = 'Dynamically generated function. No source code available.'
432 432 if (fname.endswith('.so') or fname.endswith('.dll')):
433 433 binary_file = True
434 434 out.writeln(header('File:\t\t')+fname)
435 435 except:
436 436 # if anything goes wrong, we don't want to show source, so it's as
437 437 # if the file was binary
438 438 binary_file = True
439 439
440 440 # reconstruct the function definition and print it:
441 441 defln = self.__getdef(obj,oname)
442 442 if defln:
443 443 out.write(header('Definition:\t')+self.format(defln))
444 444
445 445 # Docstrings only in detail 0 mode, since source contains them (we
446 446 # avoid repetitions). If source fails, we add them back, see below.
447 447 if ds and detail_level == 0:
448 448 out.writeln(header('Docstring:\n') + indent(ds))
449 449
450 450 # Original source code for any callable
451 451 if detail_level:
452 452 # Flush the source cache because inspect can return out-of-date
453 453 # source
454 454 linecache.checkcache()
455 455 source_success = False
456 456 try:
457 457 try:
458 458 src = getsource(obj,binary_file)
459 459 except TypeError:
460 460 if hasattr(obj,'__class__'):
461 461 src = getsource(obj.__class__,binary_file)
462 462 if src is not None:
463 463 source = self.format(src)
464 464 out.write(header('Source:\n')+source.rstrip())
465 465 source_success = True
466 466 except Exception, msg:
467 467 pass
468 468
469 469 if ds and not source_success:
470 470 out.writeln(header('Docstring [source file open failed]:\n')
471 471 + indent(ds))
472 472
473 473 # Constructor docstring for classes
474 474 if inspect.isclass(obj):
475 475 # reconstruct the function definition and print it:
476 476 try:
477 477 obj_init = obj.__init__
478 478 except AttributeError:
479 479 init_def = init_ds = None
480 480 else:
481 481 init_def = self.__getdef(obj_init,oname)
482 482 init_ds = getdoc(obj_init)
483 483 # Skip Python's auto-generated docstrings
484 484 if init_ds and \
485 485 init_ds.startswith('x.__init__(...) initializes'):
486 486 init_ds = None
487 487
488 488 if init_def or init_ds:
489 489 out.writeln(header('\nConstructor information:'))
490 490 if init_def:
491 491 out.write(header('Definition:\t')+ self.format(init_def))
492 492 if init_ds:
493 493 out.writeln(header('Docstring:\n') + indent(init_ds))
494 494 # and class docstring for instances:
495 495 elif obj_type is types.InstanceType or \
496 496 isinstance(obj,object):
497 497
498 498 # First, check whether the instance docstring is identical to the
499 499 # class one, and print it separately if they don't coincide. In
500 500 # most cases they will, but it's nice to print all the info for
501 501 # objects which use instance-customized docstrings.
502 502 if ds:
503 503 try:
504 504 cls = getattr(obj,'__class__')
505 505 except:
506 506 class_ds = None
507 507 else:
508 508 class_ds = getdoc(cls)
509 509 # Skip Python's auto-generated docstrings
510 510 if class_ds and \
511 511 (class_ds.startswith('function(code, globals[,') or \
512 512 class_ds.startswith('instancemethod(function, instance,') or \
513 513 class_ds.startswith('module(name[,') ):
514 514 class_ds = None
515 515 if class_ds and ds != class_ds:
516 516 out.writeln(header('Class Docstring:\n') +
517 517 indent(class_ds))
518 518
519 519 # Next, try to show constructor docstrings
520 520 try:
521 521 init_ds = getdoc(obj.__init__)
522 522 # Skip Python's auto-generated docstrings
523 523 if init_ds and \
524 524 init_ds.startswith('x.__init__(...) initializes'):
525 525 init_ds = None
526 526 except AttributeError:
527 527 init_ds = None
528 528 if init_ds:
529 529 out.writeln(header('Constructor Docstring:\n') +
530 530 indent(init_ds))
531 531
532 532 # Call form docstring for callable instances
533 533 if hasattr(obj,'__call__'):
534 534 #out.writeln(header('Callable:\t')+'Yes')
535 535 call_def = self.__getdef(obj.__call__,oname)
536 536 #if call_def is None:
537 537 # out.writeln(header('Call def:\t')+
538 538 # 'Calling definition not available.')
539 539 if call_def is not None:
540 540 out.writeln(header('Call def:\t')+self.format(call_def))
541 541 call_ds = getdoc(obj.__call__)
542 542 # Skip Python's auto-generated docstrings
543 543 if call_ds and call_ds.startswith('x.__call__(...) <==> x(...)'):
544 544 call_ds = None
545 545 if call_ds:
546 546 out.writeln(header('Call docstring:\n') + indent(call_ds))
547 547
548 548 # Finally send to printer/pager
549 549 output = out.getvalue()
550 550 if output:
551 551 page(output)
552 552 # end pinfo
553 553
554 554 def psearch(self,pattern,ns_table,ns_search=[],
555 555 ignore_case=False,show_all=False):
556 556 """Search namespaces with wildcards for objects.
557 557
558 558 Arguments:
559 559
560 560 - pattern: string containing shell-like wildcards to use in namespace
561 561 searches and optionally a type specification to narrow the search to
562 562 objects of that type.
563 563
564 564 - ns_table: dict of name->namespaces for search.
565 565
566 566 Optional arguments:
567 567
568 568 - ns_search: list of namespace names to include in search.
569 569
570 570 - ignore_case(False): make the search case-insensitive.
571 571
572 572 - show_all(False): show all names, including those starting with
573 573 underscores.
574 574 """
575 575 #print 'ps pattern:<%r>' % pattern # dbg
576 576
577 577 # defaults
578 578 type_pattern = 'all'
579 579 filter = ''
580 580
581 581 cmds = pattern.split()
582 582 len_cmds = len(cmds)
583 583 if len_cmds == 1:
584 584 # Only filter pattern given
585 585 filter = cmds[0]
586 586 elif len_cmds == 2:
587 587 # Both filter and type specified
588 588 filter,type_pattern = cmds
589 589 else:
590 590 raise ValueError('invalid argument string for psearch: <%s>' %
591 591 pattern)
592 592
593 593 # filter search namespaces
594 594 for name in ns_search:
595 595 if name not in ns_table:
596 596 raise ValueError('invalid namespace <%s>. Valid names: %s' %
597 597 (name,ns_table.keys()))
598 598
599 599 #print 'type_pattern:',type_pattern # dbg
600 600 search_result = []
601 601 for ns_name in ns_search:
602 602 ns = ns_table[ns_name]
603 603 tmp_res = list(list_namespace(ns,type_pattern,filter,
604 604 ignore_case=ignore_case,
605 605 show_all=show_all))
606 606 search_result.extend(tmp_res)
607 607 search_result.sort()
608 608
609 609 page('\n'.join(search_result))
@@ -1,307 +1,307 b''
1 1 #!/usr/bin/env python
2 2 # encoding: utf-8
3 3 """
4 4 Paging capabilities for IPython.core
5 5
6 6 Authors:
7 7
8 8 * Brian Granger
9 9 * Fernando Perez
10 10
11 11 Notes
12 12 -----
13 13
14 14 For now this uses ipapi, so it can't be in IPython.utils. If we can get
15 15 rid of that dependency, we could move it there.
16 16 -----
17 17 """
18 18
19 19 #-----------------------------------------------------------------------------
20 20 # Copyright (C) 2008-2009 The IPython Development Team
21 21 #
22 22 # Distributed under the terms of the BSD License. The full license is in
23 23 # the file COPYING, distributed as part of this software.
24 24 #-----------------------------------------------------------------------------
25 25
26 26 #-----------------------------------------------------------------------------
27 27 # Imports
28 28 #-----------------------------------------------------------------------------
29 29
30 30 import os
31 31 import re
32 32 import sys
33 33 import tempfile
34 34
35 35 from IPython.core import ipapi
36 36 from IPython.core.error import TryNext
37 37 from IPython.utils.cursesimport import use_curses
38 38 from IPython.utils.data import chop
39 from IPython.utils.io import Term
39 import IPython.utils.io
40 40 from IPython.utils.process import xsys
41 41 from IPython.utils.terminal import get_terminal_size
42 42
43 43
44 44 #-----------------------------------------------------------------------------
45 45 # Classes and functions
46 46 #-----------------------------------------------------------------------------
47 47
48 48 esc_re = re.compile(r"(\x1b[^m]+m)")
49 49
50 50 def page_dumb(strng, start=0, screen_lines=25):
51 51 """Very dumb 'pager' in Python, for when nothing else works.
52 52
53 53 Only moves forward, same interface as page(), except for pager_cmd and
54 54 mode."""
55 55
56 56 out_ln = strng.splitlines()[start:]
57 57 screens = chop(out_ln,screen_lines-1)
58 58 if len(screens) == 1:
59 print >>Term.cout, os.linesep.join(screens[0])
59 print >>IPython.utils.io.Term.cout, os.linesep.join(screens[0])
60 60 else:
61 61 last_escape = ""
62 62 for scr in screens[0:-1]:
63 63 hunk = os.linesep.join(scr)
64 print >>Term.cout, last_escape + hunk
64 print >>IPython.utils.io.Term.cout, last_escape + hunk
65 65 if not page_more():
66 66 return
67 67 esc_list = esc_re.findall(hunk)
68 68 if len(esc_list) > 0:
69 69 last_escape = esc_list[-1]
70 print >>Term.cout, last_escape + os.linesep.join(screens[-1])
70 print >>IPython.utils.io.Term.cout, last_escape + os.linesep.join(screens[-1])
71 71
72 72
73 73 def page(strng, start=0, screen_lines=0, pager_cmd=None):
74 74 """Print a string, piping through a pager after a certain length.
75 75
76 76 The screen_lines parameter specifies the number of *usable* lines of your
77 77 terminal screen (total lines minus lines you need to reserve to show other
78 78 information).
79 79
80 80 If you set screen_lines to a number <=0, page() will try to auto-determine
81 81 your screen size and will only use up to (screen_size+screen_lines) for
82 82 printing, paging after that. That is, if you want auto-detection but need
83 83 to reserve the bottom 3 lines of the screen, use screen_lines = -3, and for
84 84 auto-detection without any lines reserved simply use screen_lines = 0.
85 85
86 86 If a string won't fit in the allowed lines, it is sent through the
87 87 specified pager command. If none given, look for PAGER in the environment,
88 88 and ultimately default to less.
89 89
90 90 If no system pager works, the string is sent through a 'dumb pager'
91 91 written in python, very simplistic.
92 92 """
93 93
94 94 # Some routines may auto-compute start offsets incorrectly and pass a
95 95 # negative value. Offset to 0 for robustness.
96 96 start = max(0, start)
97 97
98 98 # first, try the hook
99 99 ip = ipapi.get()
100 100 if ip:
101 101 try:
102 102 ip.hooks.show_in_pager(strng)
103 103 return
104 104 except TryNext:
105 105 pass
106 106
107 107 # Ugly kludge, but calling curses.initscr() flat out crashes in emacs
108 108 TERM = os.environ.get('TERM','dumb')
109 109 if TERM in ['dumb','emacs'] and os.name != 'nt':
110 110 print strng
111 111 return
112 112 # chop off the topmost part of the string we don't want to see
113 113 str_lines = strng.split(os.linesep)[start:]
114 114 str_toprint = os.linesep.join(str_lines)
115 115 num_newlines = len(str_lines)
116 116 len_str = len(str_toprint)
117 117
118 118 # Dumb heuristics to guesstimate number of on-screen lines the string
119 119 # takes. Very basic, but good enough for docstrings in reasonable
120 120 # terminals. If someone later feels like refining it, it's not hard.
121 121 numlines = max(num_newlines,int(len_str/80)+1)
122 122
123 123 screen_lines_def = get_terminal_size()[1]
124 124
125 125 # auto-determine screen size
126 126 if screen_lines <= 0:
127 127 if (TERM=='xterm' or TERM=='xterm-color') and sys.platform != 'sunos5':
128 128 local_use_curses = use_curses
129 129 else:
130 130 # curses causes problems on many terminals other than xterm, and
131 131 # some termios calls lock up on Sun OS5.
132 132 local_use_curses = False
133 133 if local_use_curses:
134 134 import termios
135 135 import curses
136 136 # There is a bug in curses, where *sometimes* it fails to properly
137 137 # initialize, and then after the endwin() call is made, the
138 138 # terminal is left in an unusable state. Rather than trying to
139 139 # check everytime for this (by requesting and comparing termios
140 140 # flags each time), we just save the initial terminal state and
141 141 # unconditionally reset it every time. It's cheaper than making
142 142 # the checks.
143 143 term_flags = termios.tcgetattr(sys.stdout)
144 144 scr = curses.initscr()
145 145 screen_lines_real,screen_cols = scr.getmaxyx()
146 146 curses.endwin()
147 147 # Restore terminal state in case endwin() didn't.
148 148 termios.tcsetattr(sys.stdout,termios.TCSANOW,term_flags)
149 149 # Now we have what we needed: the screen size in rows/columns
150 150 screen_lines += screen_lines_real
151 151 #print '***Screen size:',screen_lines_real,'lines x',\
152 152 #screen_cols,'columns.' # dbg
153 153 else:
154 154 screen_lines += screen_lines_def
155 155
156 156 #print 'numlines',numlines,'screenlines',screen_lines # dbg
157 157 if numlines <= screen_lines :
158 158 #print '*** normal print' # dbg
159 print >>Term.cout, str_toprint
159 print >>IPython.utils.io.Term.cout, str_toprint
160 160 else:
161 161 # Try to open pager and default to internal one if that fails.
162 162 # All failure modes are tagged as 'retval=1', to match the return
163 163 # value of a failed system command. If any intermediate attempt
164 164 # sets retval to 1, at the end we resort to our own page_dumb() pager.
165 165 pager_cmd = get_pager_cmd(pager_cmd)
166 166 pager_cmd += ' ' + get_pager_start(pager_cmd,start)
167 167 if os.name == 'nt':
168 168 if pager_cmd.startswith('type'):
169 169 # The default WinXP 'type' command is failing on complex strings.
170 170 retval = 1
171 171 else:
172 172 tmpname = tempfile.mktemp('.txt')
173 173 tmpfile = file(tmpname,'wt')
174 174 tmpfile.write(strng)
175 175 tmpfile.close()
176 176 cmd = "%s < %s" % (pager_cmd,tmpname)
177 177 if os.system(cmd):
178 178 retval = 1
179 179 else:
180 180 retval = None
181 181 os.remove(tmpname)
182 182 else:
183 183 try:
184 184 retval = None
185 185 # if I use popen4, things hang. No idea why.
186 186 #pager,shell_out = os.popen4(pager_cmd)
187 187 pager = os.popen(pager_cmd,'w')
188 188 pager.write(strng)
189 189 pager.close()
190 190 retval = pager.close() # success returns None
191 191 except IOError,msg: # broken pipe when user quits
192 192 if msg.args == (32,'Broken pipe'):
193 193 retval = None
194 194 else:
195 195 retval = 1
196 196 except OSError:
197 197 # Other strange problems, sometimes seen in Win2k/cygwin
198 198 retval = 1
199 199 if retval is not None:
200 200 page_dumb(strng,screen_lines=screen_lines)
201 201
202 202
203 203 def page_file(fname, start=0, pager_cmd=None):
204 204 """Page a file, using an optional pager command and starting line.
205 205 """
206 206
207 207 pager_cmd = get_pager_cmd(pager_cmd)
208 208 pager_cmd += ' ' + get_pager_start(pager_cmd,start)
209 209
210 210 try:
211 211 if os.environ['TERM'] in ['emacs','dumb']:
212 212 raise EnvironmentError
213 213 xsys(pager_cmd + ' ' + fname)
214 214 except:
215 215 try:
216 216 if start > 0:
217 217 start -= 1
218 218 page(open(fname).read(),start)
219 219 except:
220 220 print 'Unable to show file',`fname`
221 221
222 222
223 223 def get_pager_cmd(pager_cmd=None):
224 224 """Return a pager command.
225 225
226 226 Makes some attempts at finding an OS-correct one.
227 227 """
228 228 if os.name == 'posix':
229 229 default_pager_cmd = 'less -r' # -r for color control sequences
230 230 elif os.name in ['nt','dos']:
231 231 default_pager_cmd = 'type'
232 232
233 233 if pager_cmd is None:
234 234 try:
235 235 pager_cmd = os.environ['PAGER']
236 236 except:
237 237 pager_cmd = default_pager_cmd
238 238 return pager_cmd
239 239
240 240
241 241 def get_pager_start(pager, start):
242 242 """Return the string for paging files with an offset.
243 243
244 244 This is the '+N' argument which less and more (under Unix) accept.
245 245 """
246 246
247 247 if pager in ['less','more']:
248 248 if start:
249 249 start_string = '+' + str(start)
250 250 else:
251 251 start_string = ''
252 252 else:
253 253 start_string = ''
254 254 return start_string
255 255
256 256
257 257 # (X)emacs on win32 doesn't like to be bypassed with msvcrt.getch()
258 258 if os.name == 'nt' and os.environ.get('TERM','dumb') != 'emacs':
259 259 import msvcrt
260 260 def page_more():
261 261 """ Smart pausing between pages
262 262
263 263 @return: True if need print more lines, False if quit
264 264 """
265 Term.cout.write('---Return to continue, q to quit--- ')
265 IPython.utils.io.Term.cout.write('---Return to continue, q to quit--- ')
266 266 ans = msvcrt.getch()
267 267 if ans in ("q", "Q"):
268 268 result = False
269 269 else:
270 270 result = True
271 Term.cout.write("\b"*37 + " "*37 + "\b"*37)
271 IPython.utils.io.Term.cout.write("\b"*37 + " "*37 + "\b"*37)
272 272 return result
273 273 else:
274 274 def page_more():
275 275 ans = raw_input('---Return to continue, q to quit--- ')
276 276 if ans.lower().startswith('q'):
277 277 return False
278 278 else:
279 279 return True
280 280
281 281
282 282 def snip_print(str,width = 75,print_full = 0,header = ''):
283 283 """Print a string snipping the midsection to fit in width.
284 284
285 285 print_full: mode control:
286 286 - 0: only snip long strings
287 287 - 1: send to page() directly.
288 288 - 2: snip long strings and ask for full length viewing with page()
289 289 Return 1 if snipping was necessary, 0 otherwise."""
290 290
291 291 if print_full == 1:
292 292 page(header+str)
293 293 return 0
294 294
295 295 print header,
296 296 if len(str) < width:
297 297 print str
298 298 snip = 0
299 299 else:
300 300 whalf = int((width -5)/2)
301 301 print str[:whalf] + ' <...> ' + str[-whalf:]
302 302 snip = 1
303 303 if snip and print_full == 2:
304 304 if raw_input(header+' Snipped. View (y/n)? [N]').lower() == 'y':
305 305 page(str)
306 306 return snip
307 307
@@ -1,1022 +1,1022 b''
1 1 #!/usr/bin/env python
2 2 # encoding: utf-8
3 3 """
4 4 Prefiltering components.
5 5
6 6 Prefilters transform user input before it is exec'd by Python. These
7 7 transforms are used to implement additional syntax such as !ls and %magic.
8 8
9 9 Authors:
10 10
11 11 * Brian Granger
12 12 * Fernando Perez
13 13 * Dan Milstein
14 14 * Ville Vainio
15 15 """
16 16
17 17 #-----------------------------------------------------------------------------
18 18 # Copyright (C) 2008-2009 The IPython Development Team
19 19 #
20 20 # Distributed under the terms of the BSD License. The full license is in
21 21 # the file COPYING, distributed as part of this software.
22 22 #-----------------------------------------------------------------------------
23 23
24 24 #-----------------------------------------------------------------------------
25 25 # Imports
26 26 #-----------------------------------------------------------------------------
27 27
28 28 import __builtin__
29 29 import codeop
30 30 import re
31 31
32 32 from IPython.core.alias import AliasManager
33 33 from IPython.core.autocall import IPyAutocall
34 34 from IPython.config.configurable import Configurable
35 35 from IPython.core.splitinput import split_user_input
36 36 from IPython.core.page import page
37 37
38 38 from IPython.utils.traitlets import List, Int, Any, Str, CBool, Bool, Instance
39 from IPython.utils.io import Term
39 import IPython.utils.io
40 40 from IPython.utils.text import make_quoted_expr
41 41 from IPython.utils.autoattr import auto_attr
42 42
43 43 #-----------------------------------------------------------------------------
44 44 # Global utilities, errors and constants
45 45 #-----------------------------------------------------------------------------
46 46
47 47 # Warning, these cannot be changed unless various regular expressions
48 48 # are updated in a number of places. Not great, but at least we told you.
49 49 ESC_SHELL = '!'
50 50 ESC_SH_CAP = '!!'
51 51 ESC_HELP = '?'
52 52 ESC_MAGIC = '%'
53 53 ESC_QUOTE = ','
54 54 ESC_QUOTE2 = ';'
55 55 ESC_PAREN = '/'
56 56
57 57
58 58 class PrefilterError(Exception):
59 59 pass
60 60
61 61
62 62 # RegExp to identify potential function names
63 63 re_fun_name = re.compile(r'[a-zA-Z_]([a-zA-Z0-9_.]*) *$')
64 64
65 65 # RegExp to exclude strings with this start from autocalling. In
66 66 # particular, all binary operators should be excluded, so that if foo is
67 67 # callable, foo OP bar doesn't become foo(OP bar), which is invalid. The
68 68 # characters '!=()' don't need to be checked for, as the checkPythonChars
69 69 # routine explicitely does so, to catch direct calls and rebindings of
70 70 # existing names.
71 71
72 72 # Warning: the '-' HAS TO BE AT THE END of the first group, otherwise
73 73 # it affects the rest of the group in square brackets.
74 74 re_exclude_auto = re.compile(r'^[,&^\|\*/\+-]'
75 75 r'|^is |^not |^in |^and |^or ')
76 76
77 77 # try to catch also methods for stuff in lists/tuples/dicts: off
78 78 # (experimental). For this to work, the line_split regexp would need
79 79 # to be modified so it wouldn't break things at '['. That line is
80 80 # nasty enough that I shouldn't change it until I can test it _well_.
81 81 #self.re_fun_name = re.compile (r'[a-zA-Z_]([a-zA-Z0-9_.\[\]]*) ?$')
82 82
83 83
84 84 # Handler Check Utilities
85 85 def is_shadowed(identifier, ip):
86 86 """Is the given identifier defined in one of the namespaces which shadow
87 87 the alias and magic namespaces? Note that an identifier is different
88 88 than ifun, because it can not contain a '.' character."""
89 89 # This is much safer than calling ofind, which can change state
90 90 return (identifier in ip.user_ns \
91 91 or identifier in ip.internal_ns \
92 92 or identifier in ip.ns_table['builtin'])
93 93
94 94
95 95 #-----------------------------------------------------------------------------
96 96 # The LineInfo class used throughout
97 97 #-----------------------------------------------------------------------------
98 98
99 99
100 100 class LineInfo(object):
101 101 """A single line of input and associated info.
102 102
103 103 Includes the following as properties:
104 104
105 105 line
106 106 The original, raw line
107 107
108 108 continue_prompt
109 109 Is this line a continuation in a sequence of multiline input?
110 110
111 111 pre
112 112 The initial esc character or whitespace.
113 113
114 114 pre_char
115 115 The escape character(s) in pre or the empty string if there isn't one.
116 116 Note that '!!' is a possible value for pre_char. Otherwise it will
117 117 always be a single character.
118 118
119 119 pre_whitespace
120 120 The leading whitespace from pre if it exists. If there is a pre_char,
121 121 this is just ''.
122 122
123 123 ifun
124 124 The 'function part', which is basically the maximal initial sequence
125 125 of valid python identifiers and the '.' character. This is what is
126 126 checked for alias and magic transformations, used for auto-calling,
127 127 etc.
128 128
129 129 the_rest
130 130 Everything else on the line.
131 131 """
132 132 def __init__(self, line, continue_prompt):
133 133 self.line = line
134 134 self.continue_prompt = continue_prompt
135 135 self.pre, self.ifun, self.the_rest = split_user_input(line)
136 136
137 137 self.pre_char = self.pre.strip()
138 138 if self.pre_char:
139 139 self.pre_whitespace = '' # No whitespace allowd before esc chars
140 140 else:
141 141 self.pre_whitespace = self.pre
142 142
143 143 self._oinfo = None
144 144
145 145 def ofind(self, ip):
146 146 """Do a full, attribute-walking lookup of the ifun in the various
147 147 namespaces for the given IPython InteractiveShell instance.
148 148
149 149 Return a dict with keys: found,obj,ospace,ismagic
150 150
151 151 Note: can cause state changes because of calling getattr, but should
152 152 only be run if autocall is on and if the line hasn't matched any
153 153 other, less dangerous handlers.
154 154
155 155 Does cache the results of the call, so can be called multiple times
156 156 without worrying about *further* damaging state.
157 157 """
158 158 if not self._oinfo:
159 159 # ip.shell._ofind is actually on the Magic class!
160 160 self._oinfo = ip.shell._ofind(self.ifun)
161 161 return self._oinfo
162 162
163 163 def __str__(self):
164 164 return "Lineinfo [%s|%s|%s]" %(self.pre, self.ifun, self.the_rest)
165 165
166 166
167 167 #-----------------------------------------------------------------------------
168 168 # Main Prefilter manager
169 169 #-----------------------------------------------------------------------------
170 170
171 171
172 172 class PrefilterManager(Configurable):
173 173 """Main prefilter component.
174 174
175 175 The IPython prefilter is run on all user input before it is run. The
176 176 prefilter consumes lines of input and produces transformed lines of
177 177 input.
178 178
179 179 The iplementation consists of two phases:
180 180
181 181 1. Transformers
182 182 2. Checkers and handlers
183 183
184 184 Over time, we plan on deprecating the checkers and handlers and doing
185 185 everything in the transformers.
186 186
187 187 The transformers are instances of :class:`PrefilterTransformer` and have
188 188 a single method :meth:`transform` that takes a line and returns a
189 189 transformed line. The transformation can be accomplished using any
190 190 tool, but our current ones use regular expressions for speed. We also
191 191 ship :mod:`pyparsing` in :mod:`IPython.external` for use in transformers.
192 192
193 193 After all the transformers have been run, the line is fed to the checkers,
194 194 which are instances of :class:`PrefilterChecker`. The line is passed to
195 195 the :meth:`check` method, which either returns `None` or a
196 196 :class:`PrefilterHandler` instance. If `None` is returned, the other
197 197 checkers are tried. If an :class:`PrefilterHandler` instance is returned,
198 198 the line is passed to the :meth:`handle` method of the returned
199 199 handler and no further checkers are tried.
200 200
201 201 Both transformers and checkers have a `priority` attribute, that determines
202 202 the order in which they are called. Smaller priorities are tried first.
203 203
204 204 Both transformers and checkers also have `enabled` attribute, which is
205 205 a boolean that determines if the instance is used.
206 206
207 207 Users or developers can change the priority or enabled attribute of
208 208 transformers or checkers, but they must call the :meth:`sort_checkers`
209 209 or :meth:`sort_transformers` method after changing the priority.
210 210 """
211 211
212 212 multi_line_specials = CBool(True, config=True)
213 213 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
214 214
215 215 def __init__(self, shell=None, config=None):
216 216 super(PrefilterManager, self).__init__(shell=shell, config=config)
217 217 self.shell = shell
218 218 self.init_transformers()
219 219 self.init_handlers()
220 220 self.init_checkers()
221 221
222 222 #-------------------------------------------------------------------------
223 223 # API for managing transformers
224 224 #-------------------------------------------------------------------------
225 225
226 226 def init_transformers(self):
227 227 """Create the default transformers."""
228 228 self._transformers = []
229 229 for transformer_cls in _default_transformers:
230 230 transformer_cls(
231 231 shell=self.shell, prefilter_manager=self, config=self.config
232 232 )
233 233
234 234 def sort_transformers(self):
235 235 """Sort the transformers by priority.
236 236
237 237 This must be called after the priority of a transformer is changed.
238 238 The :meth:`register_transformer` method calls this automatically.
239 239 """
240 240 self._transformers.sort(cmp=lambda x,y: x.priority-y.priority)
241 241
242 242 @property
243 243 def transformers(self):
244 244 """Return a list of checkers, sorted by priority."""
245 245 return self._transformers
246 246
247 247 def register_transformer(self, transformer):
248 248 """Register a transformer instance."""
249 249 if transformer not in self._transformers:
250 250 self._transformers.append(transformer)
251 251 self.sort_transformers()
252 252
253 253 def unregister_transformer(self, transformer):
254 254 """Unregister a transformer instance."""
255 255 if transformer in self._transformers:
256 256 self._transformers.remove(transformer)
257 257
258 258 #-------------------------------------------------------------------------
259 259 # API for managing checkers
260 260 #-------------------------------------------------------------------------
261 261
262 262 def init_checkers(self):
263 263 """Create the default checkers."""
264 264 self._checkers = []
265 265 for checker in _default_checkers:
266 266 checker(
267 267 shell=self.shell, prefilter_manager=self, config=self.config
268 268 )
269 269
270 270 def sort_checkers(self):
271 271 """Sort the checkers by priority.
272 272
273 273 This must be called after the priority of a checker is changed.
274 274 The :meth:`register_checker` method calls this automatically.
275 275 """
276 276 self._checkers.sort(cmp=lambda x,y: x.priority-y.priority)
277 277
278 278 @property
279 279 def checkers(self):
280 280 """Return a list of checkers, sorted by priority."""
281 281 return self._checkers
282 282
283 283 def register_checker(self, checker):
284 284 """Register a checker instance."""
285 285 if checker not in self._checkers:
286 286 self._checkers.append(checker)
287 287 self.sort_checkers()
288 288
289 289 def unregister_checker(self, checker):
290 290 """Unregister a checker instance."""
291 291 if checker in self._checkers:
292 292 self._checkers.remove(checker)
293 293
294 294 #-------------------------------------------------------------------------
295 295 # API for managing checkers
296 296 #-------------------------------------------------------------------------
297 297
298 298 def init_handlers(self):
299 299 """Create the default handlers."""
300 300 self._handlers = {}
301 301 self._esc_handlers = {}
302 302 for handler in _default_handlers:
303 303 handler(
304 304 shell=self.shell, prefilter_manager=self, config=self.config
305 305 )
306 306
307 307 @property
308 308 def handlers(self):
309 309 """Return a dict of all the handlers."""
310 310 return self._handlers
311 311
312 312 def register_handler(self, name, handler, esc_strings):
313 313 """Register a handler instance by name with esc_strings."""
314 314 self._handlers[name] = handler
315 315 for esc_str in esc_strings:
316 316 self._esc_handlers[esc_str] = handler
317 317
318 318 def unregister_handler(self, name, handler, esc_strings):
319 319 """Unregister a handler instance by name with esc_strings."""
320 320 try:
321 321 del self._handlers[name]
322 322 except KeyError:
323 323 pass
324 324 for esc_str in esc_strings:
325 325 h = self._esc_handlers.get(esc_str)
326 326 if h is handler:
327 327 del self._esc_handlers[esc_str]
328 328
329 329 def get_handler_by_name(self, name):
330 330 """Get a handler by its name."""
331 331 return self._handlers.get(name)
332 332
333 333 def get_handler_by_esc(self, esc_str):
334 334 """Get a handler by its escape string."""
335 335 return self._esc_handlers.get(esc_str)
336 336
337 337 #-------------------------------------------------------------------------
338 338 # Main prefiltering API
339 339 #-------------------------------------------------------------------------
340 340
341 341 def prefilter_line_info(self, line_info):
342 342 """Prefilter a line that has been converted to a LineInfo object.
343 343
344 344 This implements the checker/handler part of the prefilter pipe.
345 345 """
346 346 # print "prefilter_line_info: ", line_info
347 347 handler = self.find_handler(line_info)
348 348 return handler.handle(line_info)
349 349
350 350 def find_handler(self, line_info):
351 351 """Find a handler for the line_info by trying checkers."""
352 352 for checker in self.checkers:
353 353 if checker.enabled:
354 354 handler = checker.check(line_info)
355 355 if handler:
356 356 return handler
357 357 return self.get_handler_by_name('normal')
358 358
359 359 def transform_line(self, line, continue_prompt):
360 360 """Calls the enabled transformers in order of increasing priority."""
361 361 for transformer in self.transformers:
362 362 if transformer.enabled:
363 363 line = transformer.transform(line, continue_prompt)
364 364 return line
365 365
366 366 def prefilter_line(self, line, continue_prompt=False):
367 367 """Prefilter a single input line as text.
368 368
369 369 This method prefilters a single line of text by calling the
370 370 transformers and then the checkers/handlers.
371 371 """
372 372
373 373 # print "prefilter_line: ", line, continue_prompt
374 374 # All handlers *must* return a value, even if it's blank ('').
375 375
376 376 # Lines are NOT logged here. Handlers should process the line as
377 377 # needed, update the cache AND log it (so that the input cache array
378 378 # stays synced).
379 379
380 380 # save the line away in case we crash, so the post-mortem handler can
381 381 # record it
382 382 self.shell._last_input_line = line
383 383
384 384 if not line:
385 385 # Return immediately on purely empty lines, so that if the user
386 386 # previously typed some whitespace that started a continuation
387 387 # prompt, he can break out of that loop with just an empty line.
388 388 # This is how the default python prompt works.
389 389
390 390 # Only return if the accumulated input buffer was just whitespace!
391 391 if ''.join(self.shell.buffer).isspace():
392 392 self.shell.buffer[:] = []
393 393 return ''
394 394
395 395 # At this point, we invoke our transformers.
396 396 if not continue_prompt or (continue_prompt and self.multi_line_specials):
397 397 line = self.transform_line(line, continue_prompt)
398 398
399 399 # Now we compute line_info for the checkers and handlers
400 400 line_info = LineInfo(line, continue_prompt)
401 401
402 402 # the input history needs to track even empty lines
403 403 stripped = line.strip()
404 404
405 405 normal_handler = self.get_handler_by_name('normal')
406 406 if not stripped:
407 407 if not continue_prompt:
408 408 self.shell.outputcache.prompt_count -= 1
409 409
410 410 return normal_handler.handle(line_info)
411 411
412 412 # special handlers are only allowed for single line statements
413 413 if continue_prompt and not self.multi_line_specials:
414 414 return normal_handler.handle(line_info)
415 415
416 416 prefiltered = self.prefilter_line_info(line_info)
417 417 # print "prefiltered line: %r" % prefiltered
418 418 return prefiltered
419 419
420 420 def prefilter_lines(self, lines, continue_prompt=False):
421 421 """Prefilter multiple input lines of text.
422 422
423 423 This is the main entry point for prefiltering multiple lines of
424 424 input. This simply calls :meth:`prefilter_line` for each line of
425 425 input.
426 426
427 427 This covers cases where there are multiple lines in the user entry,
428 428 which is the case when the user goes back to a multiline history
429 429 entry and presses enter.
430 430 """
431 431 llines = lines.rstrip('\n').split('\n')
432 432 # We can get multiple lines in one shot, where multiline input 'blends'
433 433 # into one line, in cases like recalling from the readline history
434 434 # buffer. We need to make sure that in such cases, we correctly
435 435 # communicate downstream which line is first and which are continuation
436 436 # ones.
437 437 if len(llines) > 1:
438 438 out = '\n'.join([self.prefilter_line(line, lnum>0)
439 439 for lnum, line in enumerate(llines) ])
440 440 else:
441 441 out = self.prefilter_line(llines[0], continue_prompt)
442 442
443 443 return out
444 444
445 445 #-----------------------------------------------------------------------------
446 446 # Prefilter transformers
447 447 #-----------------------------------------------------------------------------
448 448
449 449
450 450 class PrefilterTransformer(Configurable):
451 451 """Transform a line of user input."""
452 452
453 453 priority = Int(100, config=True)
454 454 # Transformers don't currently use shell or prefilter_manager, but as we
455 455 # move away from checkers and handlers, they will need them.
456 456 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
457 457 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
458 458 enabled = Bool(True, config=True)
459 459
460 460 def __init__(self, shell=None, prefilter_manager=None, config=None):
461 461 super(PrefilterTransformer, self).__init__(
462 462 shell=shell, prefilter_manager=prefilter_manager, config=config
463 463 )
464 464 self.prefilter_manager.register_transformer(self)
465 465
466 466 def transform(self, line, continue_prompt):
467 467 """Transform a line, returning the new one."""
468 468 return None
469 469
470 470 def __repr__(self):
471 471 return "<%s(priority=%r, enabled=%r)>" % (
472 472 self.__class__.__name__, self.priority, self.enabled)
473 473
474 474
475 475 _assign_system_re = re.compile(r'(?P<lhs>(\s*)([\w\.]+)((\s*,\s*[\w\.]+)*))'
476 476 r'\s*=\s*!(?P<cmd>.*)')
477 477
478 478
479 479 class AssignSystemTransformer(PrefilterTransformer):
480 480 """Handle the `files = !ls` syntax."""
481 481
482 482 priority = Int(100, config=True)
483 483
484 484 def transform(self, line, continue_prompt):
485 485 m = _assign_system_re.match(line)
486 486 if m is not None:
487 487 cmd = m.group('cmd')
488 488 lhs = m.group('lhs')
489 489 expr = make_quoted_expr("sc -l =%s" % cmd)
490 490 new_line = '%s = get_ipython().magic(%s)' % (lhs, expr)
491 491 return new_line
492 492 return line
493 493
494 494
495 495 _assign_magic_re = re.compile(r'(?P<lhs>(\s*)([\w\.]+)((\s*,\s*[\w\.]+)*))'
496 496 r'\s*=\s*%(?P<cmd>.*)')
497 497
498 498 class AssignMagicTransformer(PrefilterTransformer):
499 499 """Handle the `a = %who` syntax."""
500 500
501 501 priority = Int(200, config=True)
502 502
503 503 def transform(self, line, continue_prompt):
504 504 m = _assign_magic_re.match(line)
505 505 if m is not None:
506 506 cmd = m.group('cmd')
507 507 lhs = m.group('lhs')
508 508 expr = make_quoted_expr(cmd)
509 509 new_line = '%s = get_ipython().magic(%s)' % (lhs, expr)
510 510 return new_line
511 511 return line
512 512
513 513
514 514 _classic_prompt_re = re.compile(r'(^[ \t]*>>> |^[ \t]*\.\.\. )')
515 515
516 516 class PyPromptTransformer(PrefilterTransformer):
517 517 """Handle inputs that start with '>>> ' syntax."""
518 518
519 519 priority = Int(50, config=True)
520 520
521 521 def transform(self, line, continue_prompt):
522 522
523 523 if not line or line.isspace() or line.strip() == '...':
524 524 # This allows us to recognize multiple input prompts separated by
525 525 # blank lines and pasted in a single chunk, very common when
526 526 # pasting doctests or long tutorial passages.
527 527 return ''
528 528 m = _classic_prompt_re.match(line)
529 529 if m:
530 530 return line[len(m.group(0)):]
531 531 else:
532 532 return line
533 533
534 534
535 535 _ipy_prompt_re = re.compile(r'(^[ \t]*In \[\d+\]: |^[ \t]*\ \ \ \.\.\.+: )')
536 536
537 537 class IPyPromptTransformer(PrefilterTransformer):
538 538 """Handle inputs that start classic IPython prompt syntax."""
539 539
540 540 priority = Int(50, config=True)
541 541
542 542 def transform(self, line, continue_prompt):
543 543
544 544 if not line or line.isspace() or line.strip() == '...':
545 545 # This allows us to recognize multiple input prompts separated by
546 546 # blank lines and pasted in a single chunk, very common when
547 547 # pasting doctests or long tutorial passages.
548 548 return ''
549 549 m = _ipy_prompt_re.match(line)
550 550 if m:
551 551 return line[len(m.group(0)):]
552 552 else:
553 553 return line
554 554
555 555 #-----------------------------------------------------------------------------
556 556 # Prefilter checkers
557 557 #-----------------------------------------------------------------------------
558 558
559 559
560 560 class PrefilterChecker(Configurable):
561 561 """Inspect an input line and return a handler for that line."""
562 562
563 563 priority = Int(100, config=True)
564 564 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
565 565 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
566 566 enabled = Bool(True, config=True)
567 567
568 568 def __init__(self, shell=None, prefilter_manager=None, config=None):
569 569 super(PrefilterChecker, self).__init__(
570 570 shell=shell, prefilter_manager=prefilter_manager, config=config
571 571 )
572 572 self.prefilter_manager.register_checker(self)
573 573
574 574 def check(self, line_info):
575 575 """Inspect line_info and return a handler instance or None."""
576 576 return None
577 577
578 578 def __repr__(self):
579 579 return "<%s(priority=%r, enabled=%r)>" % (
580 580 self.__class__.__name__, self.priority, self.enabled)
581 581
582 582
583 583 class EmacsChecker(PrefilterChecker):
584 584
585 585 priority = Int(100, config=True)
586 586 enabled = Bool(False, config=True)
587 587
588 588 def check(self, line_info):
589 589 "Emacs ipython-mode tags certain input lines."
590 590 if line_info.line.endswith('# PYTHON-MODE'):
591 591 return self.prefilter_manager.get_handler_by_name('emacs')
592 592 else:
593 593 return None
594 594
595 595
596 596 class ShellEscapeChecker(PrefilterChecker):
597 597
598 598 priority = Int(200, config=True)
599 599
600 600 def check(self, line_info):
601 601 if line_info.line.lstrip().startswith(ESC_SHELL):
602 602 return self.prefilter_manager.get_handler_by_name('shell')
603 603
604 604
605 605 class IPyAutocallChecker(PrefilterChecker):
606 606
607 607 priority = Int(300, config=True)
608 608
609 609 def check(self, line_info):
610 610 "Instances of IPyAutocall in user_ns get autocalled immediately"
611 611 obj = self.shell.user_ns.get(line_info.ifun, None)
612 612 if isinstance(obj, IPyAutocall):
613 613 obj.set_ip(self.shell)
614 614 return self.prefilter_manager.get_handler_by_name('auto')
615 615 else:
616 616 return None
617 617
618 618
619 619 class MultiLineMagicChecker(PrefilterChecker):
620 620
621 621 priority = Int(400, config=True)
622 622
623 623 def check(self, line_info):
624 624 "Allow ! and !! in multi-line statements if multi_line_specials is on"
625 625 # Note that this one of the only places we check the first character of
626 626 # ifun and *not* the pre_char. Also note that the below test matches
627 627 # both ! and !!.
628 628 if line_info.continue_prompt \
629 629 and self.prefilter_manager.multi_line_specials:
630 630 if line_info.ifun.startswith(ESC_MAGIC):
631 631 return self.prefilter_manager.get_handler_by_name('magic')
632 632 else:
633 633 return None
634 634
635 635
636 636 class EscCharsChecker(PrefilterChecker):
637 637
638 638 priority = Int(500, config=True)
639 639
640 640 def check(self, line_info):
641 641 """Check for escape character and return either a handler to handle it,
642 642 or None if there is no escape char."""
643 643 if line_info.line[-1] == ESC_HELP \
644 644 and line_info.pre_char != ESC_SHELL \
645 645 and line_info.pre_char != ESC_SH_CAP:
646 646 # the ? can be at the end, but *not* for either kind of shell escape,
647 647 # because a ? can be a vaild final char in a shell cmd
648 648 return self.prefilter_manager.get_handler_by_name('help')
649 649 else:
650 650 # This returns None like it should if no handler exists
651 651 return self.prefilter_manager.get_handler_by_esc(line_info.pre_char)
652 652
653 653
654 654 class AssignmentChecker(PrefilterChecker):
655 655
656 656 priority = Int(600, config=True)
657 657
658 658 def check(self, line_info):
659 659 """Check to see if user is assigning to a var for the first time, in
660 660 which case we want to avoid any sort of automagic / autocall games.
661 661
662 662 This allows users to assign to either alias or magic names true python
663 663 variables (the magic/alias systems always take second seat to true
664 664 python code). E.g. ls='hi', or ls,that=1,2"""
665 665 if line_info.the_rest:
666 666 if line_info.the_rest[0] in '=,':
667 667 return self.prefilter_manager.get_handler_by_name('normal')
668 668 else:
669 669 return None
670 670
671 671
672 672 class AutoMagicChecker(PrefilterChecker):
673 673
674 674 priority = Int(700, config=True)
675 675
676 676 def check(self, line_info):
677 677 """If the ifun is magic, and automagic is on, run it. Note: normal,
678 678 non-auto magic would already have been triggered via '%' in
679 679 check_esc_chars. This just checks for automagic. Also, before
680 680 triggering the magic handler, make sure that there is nothing in the
681 681 user namespace which could shadow it."""
682 682 if not self.shell.automagic or not hasattr(self.shell,'magic_'+line_info.ifun):
683 683 return None
684 684
685 685 # We have a likely magic method. Make sure we should actually call it.
686 686 if line_info.continue_prompt and not self.prefilter_manager.multi_line_specials:
687 687 return None
688 688
689 689 head = line_info.ifun.split('.',1)[0]
690 690 if is_shadowed(head, self.shell):
691 691 return None
692 692
693 693 return self.prefilter_manager.get_handler_by_name('magic')
694 694
695 695
696 696 class AliasChecker(PrefilterChecker):
697 697
698 698 priority = Int(800, config=True)
699 699
700 700 def check(self, line_info):
701 701 "Check if the initital identifier on the line is an alias."
702 702 # Note: aliases can not contain '.'
703 703 head = line_info.ifun.split('.',1)[0]
704 704 if line_info.ifun not in self.shell.alias_manager \
705 705 or head not in self.shell.alias_manager \
706 706 or is_shadowed(head, self.shell):
707 707 return None
708 708
709 709 return self.prefilter_manager.get_handler_by_name('alias')
710 710
711 711
712 712 class PythonOpsChecker(PrefilterChecker):
713 713
714 714 priority = Int(900, config=True)
715 715
716 716 def check(self, line_info):
717 717 """If the 'rest' of the line begins with a function call or pretty much
718 718 any python operator, we should simply execute the line (regardless of
719 719 whether or not there's a possible autocall expansion). This avoids
720 720 spurious (and very confusing) geattr() accesses."""
721 721 if line_info.the_rest and line_info.the_rest[0] in '!=()<>,+*/%^&|':
722 722 return self.prefilter_manager.get_handler_by_name('normal')
723 723 else:
724 724 return None
725 725
726 726
727 727 class AutocallChecker(PrefilterChecker):
728 728
729 729 priority = Int(1000, config=True)
730 730
731 731 def check(self, line_info):
732 732 "Check if the initial word/function is callable and autocall is on."
733 733 if not self.shell.autocall:
734 734 return None
735 735
736 736 oinfo = line_info.ofind(self.shell) # This can mutate state via getattr
737 737 if not oinfo['found']:
738 738 return None
739 739
740 740 if callable(oinfo['obj']) \
741 741 and (not re_exclude_auto.match(line_info.the_rest)) \
742 742 and re_fun_name.match(line_info.ifun):
743 743 return self.prefilter_manager.get_handler_by_name('auto')
744 744 else:
745 745 return None
746 746
747 747
748 748 #-----------------------------------------------------------------------------
749 749 # Prefilter handlers
750 750 #-----------------------------------------------------------------------------
751 751
752 752
753 753 class PrefilterHandler(Configurable):
754 754
755 755 handler_name = Str('normal')
756 756 esc_strings = List([])
757 757 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
758 758 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
759 759
760 760 def __init__(self, shell=None, prefilter_manager=None, config=None):
761 761 super(PrefilterHandler, self).__init__(
762 762 shell=shell, prefilter_manager=prefilter_manager, config=config
763 763 )
764 764 self.prefilter_manager.register_handler(
765 765 self.handler_name,
766 766 self,
767 767 self.esc_strings
768 768 )
769 769
770 770 def handle(self, line_info):
771 771 # print "normal: ", line_info
772 772 """Handle normal input lines. Use as a template for handlers."""
773 773
774 774 # With autoindent on, we need some way to exit the input loop, and I
775 775 # don't want to force the user to have to backspace all the way to
776 776 # clear the line. The rule will be in this case, that either two
777 777 # lines of pure whitespace in a row, or a line of pure whitespace but
778 778 # of a size different to the indent level, will exit the input loop.
779 779 line = line_info.line
780 780 continue_prompt = line_info.continue_prompt
781 781
782 782 if (continue_prompt and
783 783 self.shell.autoindent and
784 784 line.isspace() and
785 785
786 786 (0 < abs(len(line) - self.shell.indent_current_nsp) <= 2
787 787 or
788 788 not self.shell.buffer
789 789 or
790 790 (self.shell.buffer[-1]).isspace()
791 791 )
792 792 ):
793 793 line = ''
794 794
795 795 self.shell.log(line, line, continue_prompt)
796 796 return line
797 797
798 798 def __str__(self):
799 799 return "<%s(name=%s)>" % (self.__class__.__name__, self.handler_name)
800 800
801 801
802 802 class AliasHandler(PrefilterHandler):
803 803
804 804 handler_name = Str('alias')
805 805
806 806 def handle(self, line_info):
807 807 """Handle alias input lines. """
808 808 transformed = self.shell.alias_manager.expand_aliases(line_info.ifun,line_info.the_rest)
809 809 # pre is needed, because it carries the leading whitespace. Otherwise
810 810 # aliases won't work in indented sections.
811 811 line_out = '%sget_ipython().system(%s)' % (line_info.pre_whitespace,
812 812 make_quoted_expr(transformed))
813 813
814 814 self.shell.log(line_info.line, line_out, line_info.continue_prompt)
815 815 return line_out
816 816
817 817
818 818 class ShellEscapeHandler(PrefilterHandler):
819 819
820 820 handler_name = Str('shell')
821 821 esc_strings = List([ESC_SHELL, ESC_SH_CAP])
822 822
823 823 def handle(self, line_info):
824 824 """Execute the line in a shell, empty return value"""
825 825 magic_handler = self.prefilter_manager.get_handler_by_name('magic')
826 826
827 827 line = line_info.line
828 828 if line.lstrip().startswith(ESC_SH_CAP):
829 829 # rewrite LineInfo's line, ifun and the_rest to properly hold the
830 830 # call to %sx and the actual command to be executed, so
831 831 # handle_magic can work correctly. Note that this works even if
832 832 # the line is indented, so it handles multi_line_specials
833 833 # properly.
834 834 new_rest = line.lstrip()[2:]
835 835 line_info.line = '%ssx %s' % (ESC_MAGIC, new_rest)
836 836 line_info.ifun = 'sx'
837 837 line_info.the_rest = new_rest
838 838 return magic_handler.handle(line_info)
839 839 else:
840 840 cmd = line.lstrip().lstrip(ESC_SHELL)
841 841 line_out = '%sget_ipython().system(%s)' % (line_info.pre_whitespace,
842 842 make_quoted_expr(cmd))
843 843 # update cache/log and return
844 844 self.shell.log(line, line_out, line_info.continue_prompt)
845 845 return line_out
846 846
847 847
848 848 class MagicHandler(PrefilterHandler):
849 849
850 850 handler_name = Str('magic')
851 851 esc_strings = List([ESC_MAGIC])
852 852
853 853 def handle(self, line_info):
854 854 """Execute magic functions."""
855 855 ifun = line_info.ifun
856 856 the_rest = line_info.the_rest
857 857 cmd = '%sget_ipython().magic(%s)' % (line_info.pre_whitespace,
858 858 make_quoted_expr(ifun + " " + the_rest))
859 859 self.shell.log(line_info.line, cmd, line_info.continue_prompt)
860 860 return cmd
861 861
862 862
863 863 class AutoHandler(PrefilterHandler):
864 864
865 865 handler_name = Str('auto')
866 866 esc_strings = List([ESC_PAREN, ESC_QUOTE, ESC_QUOTE2])
867 867
868 868 def handle(self, line_info):
869 869 """Handle lines which can be auto-executed, quoting if requested."""
870 870 line = line_info.line
871 871 ifun = line_info.ifun
872 872 the_rest = line_info.the_rest
873 873 pre = line_info.pre
874 874 continue_prompt = line_info.continue_prompt
875 875 obj = line_info.ofind(self)['obj']
876 876 #print 'pre <%s> ifun <%s> rest <%s>' % (pre,ifun,the_rest) # dbg
877 877
878 878 # This should only be active for single-line input!
879 879 if continue_prompt:
880 880 self.shell.log(line,line,continue_prompt)
881 881 return line
882 882
883 883 force_auto = isinstance(obj, IPyAutocall)
884 884 auto_rewrite = True
885 885
886 886 if pre == ESC_QUOTE:
887 887 # Auto-quote splitting on whitespace
888 888 newcmd = '%s("%s")' % (ifun,'", "'.join(the_rest.split()) )
889 889 elif pre == ESC_QUOTE2:
890 890 # Auto-quote whole string
891 891 newcmd = '%s("%s")' % (ifun,the_rest)
892 892 elif pre == ESC_PAREN:
893 893 newcmd = '%s(%s)' % (ifun,",".join(the_rest.split()))
894 894 else:
895 895 # Auto-paren.
896 896 # We only apply it to argument-less calls if the autocall
897 897 # parameter is set to 2. We only need to check that autocall is <
898 898 # 2, since this function isn't called unless it's at least 1.
899 899 if not the_rest and (self.shell.autocall < 2) and not force_auto:
900 900 newcmd = '%s %s' % (ifun,the_rest)
901 901 auto_rewrite = False
902 902 else:
903 903 if not force_auto and the_rest.startswith('['):
904 904 if hasattr(obj,'__getitem__'):
905 905 # Don't autocall in this case: item access for an object
906 906 # which is BOTH callable and implements __getitem__.
907 907 newcmd = '%s %s' % (ifun,the_rest)
908 908 auto_rewrite = False
909 909 else:
910 910 # if the object doesn't support [] access, go ahead and
911 911 # autocall
912 912 newcmd = '%s(%s)' % (ifun.rstrip(),the_rest)
913 913 elif the_rest.endswith(';'):
914 914 newcmd = '%s(%s);' % (ifun.rstrip(),the_rest[:-1])
915 915 else:
916 916 newcmd = '%s(%s)' % (ifun.rstrip(), the_rest)
917 917
918 918 if auto_rewrite:
919 919 rw = self.shell.outputcache.prompt1.auto_rewrite() + newcmd
920 920
921 921 try:
922 922 # plain ascii works better w/ pyreadline, on some machines, so
923 923 # we use it and only print uncolored rewrite if we have unicode
924 924 rw = str(rw)
925 print >>Term.cout, rw
925 print >>IPython.utils.io.Term.cout, rw
926 926 except UnicodeEncodeError:
927 927 print "-------------->" + newcmd
928 928
929 929 # log what is now valid Python, not the actual user input (without the
930 930 # final newline)
931 931 self.shell.log(line,newcmd,continue_prompt)
932 932 return newcmd
933 933
934 934
935 935 class HelpHandler(PrefilterHandler):
936 936
937 937 handler_name = Str('help')
938 938 esc_strings = List([ESC_HELP])
939 939
940 940 def handle(self, line_info):
941 941 """Try to get some help for the object.
942 942
943 943 obj? or ?obj -> basic information.
944 944 obj?? or ??obj -> more details.
945 945 """
946 946 normal_handler = self.prefilter_manager.get_handler_by_name('normal')
947 947 line = line_info.line
948 948 # We need to make sure that we don't process lines which would be
949 949 # otherwise valid python, such as "x=1 # what?"
950 950 try:
951 951 codeop.compile_command(line)
952 952 except SyntaxError:
953 953 # We should only handle as help stuff which is NOT valid syntax
954 954 if line[0]==ESC_HELP:
955 955 line = line[1:]
956 956 elif line[-1]==ESC_HELP:
957 957 line = line[:-1]
958 958 self.shell.log(line, '#?'+line, line_info.continue_prompt)
959 959 if line:
960 960 #print 'line:<%r>' % line # dbg
961 961 self.shell.magic_pinfo(line)
962 962 else:
963 963 page(self.shell.usage, screen_lines=self.shell.usable_screen_length)
964 964 return '' # Empty string is needed here!
965 965 except:
966 966 raise
967 967 # Pass any other exceptions through to the normal handler
968 968 return normal_handler.handle(line_info)
969 969 else:
970 970 # If the code compiles ok, we should handle it normally
971 971 return normal_handler.handle(line_info)
972 972
973 973
974 974 class EmacsHandler(PrefilterHandler):
975 975
976 976 handler_name = Str('emacs')
977 977 esc_strings = List([])
978 978
979 979 def handle(self, line_info):
980 980 """Handle input lines marked by python-mode."""
981 981
982 982 # Currently, nothing is done. Later more functionality can be added
983 983 # here if needed.
984 984
985 985 # The input cache shouldn't be updated
986 986 return line_info.line
987 987
988 988
989 989 #-----------------------------------------------------------------------------
990 990 # Defaults
991 991 #-----------------------------------------------------------------------------
992 992
993 993
994 994 _default_transformers = [
995 995 AssignSystemTransformer,
996 996 AssignMagicTransformer,
997 997 PyPromptTransformer,
998 998 IPyPromptTransformer,
999 999 ]
1000 1000
1001 1001 _default_checkers = [
1002 1002 EmacsChecker,
1003 1003 ShellEscapeChecker,
1004 1004 IPyAutocallChecker,
1005 1005 MultiLineMagicChecker,
1006 1006 EscCharsChecker,
1007 1007 AssignmentChecker,
1008 1008 AutoMagicChecker,
1009 1009 AliasChecker,
1010 1010 PythonOpsChecker,
1011 1011 AutocallChecker
1012 1012 ]
1013 1013
1014 1014 _default_handlers = [
1015 1015 PrefilterHandler,
1016 1016 AliasHandler,
1017 1017 ShellEscapeHandler,
1018 1018 MagicHandler,
1019 1019 AutoHandler,
1020 1020 HelpHandler,
1021 1021 EmacsHandler
1022 1022 ]
@@ -1,639 +1,639 b''
1 1 # -*- coding: utf-8 -*-
2 2 """
3 3 Classes for handling input/output prompts.
4 4 """
5 5
6 6 #*****************************************************************************
7 7 # Copyright (C) 2008-2009 The IPython Development Team
8 8 # Copyright (C) 2001-2007 Fernando Perez <fperez@colorado.edu>
9 9 #
10 10 # Distributed under the terms of the BSD License. The full license is in
11 11 # the file COPYING, distributed as part of this software.
12 12 #*****************************************************************************
13 13
14 14 #****************************************************************************
15 15
16 16 import __builtin__
17 17 import os
18 18 import re
19 19 import socket
20 20 import sys
21 21
22 22 from IPython.core import release
23 23 from IPython.external.Itpl import ItplNS
24 24 from IPython.core.error import TryNext
25 25 from IPython.utils import coloransi
26 26 import IPython.utils.generics
27 27 from IPython.utils.warn import warn
28 from IPython.utils.io import Term
28 import IPython.utils.io
29 29
30 30 #****************************************************************************
31 31 #Color schemes for Prompts.
32 32
33 33 PromptColors = coloransi.ColorSchemeTable()
34 34 InputColors = coloransi.InputTermColors # just a shorthand
35 35 Colors = coloransi.TermColors # just a shorthand
36 36
37 37 PromptColors.add_scheme(coloransi.ColorScheme(
38 38 'NoColor',
39 39 in_prompt = InputColors.NoColor, # Input prompt
40 40 in_number = InputColors.NoColor, # Input prompt number
41 41 in_prompt2 = InputColors.NoColor, # Continuation prompt
42 42 in_normal = InputColors.NoColor, # color off (usu. Colors.Normal)
43 43
44 44 out_prompt = Colors.NoColor, # Output prompt
45 45 out_number = Colors.NoColor, # Output prompt number
46 46
47 47 normal = Colors.NoColor # color off (usu. Colors.Normal)
48 48 ))
49 49
50 50 # make some schemes as instances so we can copy them for modification easily:
51 51 __PColLinux = coloransi.ColorScheme(
52 52 'Linux',
53 53 in_prompt = InputColors.Green,
54 54 in_number = InputColors.LightGreen,
55 55 in_prompt2 = InputColors.Green,
56 56 in_normal = InputColors.Normal, # color off (usu. Colors.Normal)
57 57
58 58 out_prompt = Colors.Red,
59 59 out_number = Colors.LightRed,
60 60
61 61 normal = Colors.Normal
62 62 )
63 63 # Don't forget to enter it into the table!
64 64 PromptColors.add_scheme(__PColLinux)
65 65
66 66 # Slightly modified Linux for light backgrounds
67 67 __PColLightBG = __PColLinux.copy('LightBG')
68 68
69 69 __PColLightBG.colors.update(
70 70 in_prompt = InputColors.Blue,
71 71 in_number = InputColors.LightBlue,
72 72 in_prompt2 = InputColors.Blue
73 73 )
74 74 PromptColors.add_scheme(__PColLightBG)
75 75
76 76 del Colors,InputColors
77 77
78 78 #-----------------------------------------------------------------------------
79 79 def multiple_replace(dict, text):
80 80 """ Replace in 'text' all occurences of any key in the given
81 81 dictionary by its corresponding value. Returns the new string."""
82 82
83 83 # Function by Xavier Defrang, originally found at:
84 84 # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/81330
85 85
86 86 # Create a regular expression from the dictionary keys
87 87 regex = re.compile("(%s)" % "|".join(map(re.escape, dict.keys())))
88 88 # For each match, look-up corresponding value in dictionary
89 89 return regex.sub(lambda mo: dict[mo.string[mo.start():mo.end()]], text)
90 90
91 91 #-----------------------------------------------------------------------------
92 92 # Special characters that can be used in prompt templates, mainly bash-like
93 93
94 94 # If $HOME isn't defined (Windows), make it an absurd string so that it can
95 95 # never be expanded out into '~'. Basically anything which can never be a
96 96 # reasonable directory name will do, we just want the $HOME -> '~' operation
97 97 # to become a no-op. We pre-compute $HOME here so it's not done on every
98 98 # prompt call.
99 99
100 100 # FIXME:
101 101
102 102 # - This should be turned into a class which does proper namespace management,
103 103 # since the prompt specials need to be evaluated in a certain namespace.
104 104 # Currently it's just globals, which need to be managed manually by code
105 105 # below.
106 106
107 107 # - I also need to split up the color schemes from the prompt specials
108 108 # somehow. I don't have a clean design for that quite yet.
109 109
110 110 HOME = os.environ.get("HOME","//////:::::ZZZZZ,,,~~~")
111 111
112 112 # We precompute a few more strings here for the prompt_specials, which are
113 113 # fixed once ipython starts. This reduces the runtime overhead of computing
114 114 # prompt strings.
115 115 USER = os.environ.get("USER")
116 116 HOSTNAME = socket.gethostname()
117 117 HOSTNAME_SHORT = HOSTNAME.split(".")[0]
118 118 ROOT_SYMBOL = "$#"[os.name=='nt' or os.getuid()==0]
119 119
120 120 prompt_specials_color = {
121 121 # Prompt/history count
122 122 '%n' : '${self.col_num}' '${self.cache.prompt_count}' '${self.col_p}',
123 123 r'\#': '${self.col_num}' '${self.cache.prompt_count}' '${self.col_p}',
124 124 # Just the prompt counter number, WITHOUT any coloring wrappers, so users
125 125 # can get numbers displayed in whatever color they want.
126 126 r'\N': '${self.cache.prompt_count}',
127 127
128 128 # Prompt/history count, with the actual digits replaced by dots. Used
129 129 # mainly in continuation prompts (prompt_in2)
130 130 #r'\D': '${"."*len(str(self.cache.prompt_count))}',
131 131
132 132 # More robust form of the above expression, that uses the __builtin__
133 133 # module. Note that we can NOT use __builtins__ (note the 's'), because
134 134 # that can either be a dict or a module, and can even mutate at runtime,
135 135 # depending on the context (Python makes no guarantees on it). In
136 136 # contrast, __builtin__ is always a module object, though it must be
137 137 # explicitly imported.
138 138 r'\D': '${"."*__builtin__.len(__builtin__.str(self.cache.prompt_count))}',
139 139
140 140 # Current working directory
141 141 r'\w': '${os.getcwd()}',
142 142 # Current time
143 143 r'\t' : '${time.strftime("%H:%M:%S")}',
144 144 # Basename of current working directory.
145 145 # (use os.sep to make this portable across OSes)
146 146 r'\W' : '${os.getcwd().split("%s")[-1]}' % os.sep,
147 147 # These X<N> are an extension to the normal bash prompts. They return
148 148 # N terms of the path, after replacing $HOME with '~'
149 149 r'\X0': '${os.getcwd().replace("%s","~")}' % HOME,
150 150 r'\X1': '${self.cwd_filt(1)}',
151 151 r'\X2': '${self.cwd_filt(2)}',
152 152 r'\X3': '${self.cwd_filt(3)}',
153 153 r'\X4': '${self.cwd_filt(4)}',
154 154 r'\X5': '${self.cwd_filt(5)}',
155 155 # Y<N> are similar to X<N>, but they show '~' if it's the directory
156 156 # N+1 in the list. Somewhat like %cN in tcsh.
157 157 r'\Y0': '${self.cwd_filt2(0)}',
158 158 r'\Y1': '${self.cwd_filt2(1)}',
159 159 r'\Y2': '${self.cwd_filt2(2)}',
160 160 r'\Y3': '${self.cwd_filt2(3)}',
161 161 r'\Y4': '${self.cwd_filt2(4)}',
162 162 r'\Y5': '${self.cwd_filt2(5)}',
163 163 # Hostname up to first .
164 164 r'\h': HOSTNAME_SHORT,
165 165 # Full hostname
166 166 r'\H': HOSTNAME,
167 167 # Username of current user
168 168 r'\u': USER,
169 169 # Escaped '\'
170 170 '\\\\': '\\',
171 171 # Newline
172 172 r'\n': '\n',
173 173 # Carriage return
174 174 r'\r': '\r',
175 175 # Release version
176 176 r'\v': release.version,
177 177 # Root symbol ($ or #)
178 178 r'\$': ROOT_SYMBOL,
179 179 }
180 180
181 181 # A copy of the prompt_specials dictionary but with all color escapes removed,
182 182 # so we can correctly compute the prompt length for the auto_rewrite method.
183 183 prompt_specials_nocolor = prompt_specials_color.copy()
184 184 prompt_specials_nocolor['%n'] = '${self.cache.prompt_count}'
185 185 prompt_specials_nocolor[r'\#'] = '${self.cache.prompt_count}'
186 186
187 187 # Add in all the InputTermColors color escapes as valid prompt characters.
188 188 # They all get added as \\C_COLORNAME, so that we don't have any conflicts
189 189 # with a color name which may begin with a letter used by any other of the
190 190 # allowed specials. This of course means that \\C will never be allowed for
191 191 # anything else.
192 192 input_colors = coloransi.InputTermColors
193 193 for _color in dir(input_colors):
194 194 if _color[0] != '_':
195 195 c_name = r'\C_'+_color
196 196 prompt_specials_color[c_name] = getattr(input_colors,_color)
197 197 prompt_specials_nocolor[c_name] = ''
198 198
199 199 # we default to no color for safety. Note that prompt_specials is a global
200 200 # variable used by all prompt objects.
201 201 prompt_specials = prompt_specials_nocolor
202 202
203 203 #-----------------------------------------------------------------------------
204 204 def str_safe(arg):
205 205 """Convert to a string, without ever raising an exception.
206 206
207 207 If str(arg) fails, <ERROR: ... > is returned, where ... is the exception
208 208 error message."""
209 209
210 210 try:
211 211 out = str(arg)
212 212 except UnicodeError:
213 213 try:
214 214 out = arg.encode('utf_8','replace')
215 215 except Exception,msg:
216 216 # let's keep this little duplication here, so that the most common
217 217 # case doesn't suffer from a double try wrapping.
218 218 out = '<ERROR: %s>' % msg
219 219 except Exception,msg:
220 220 out = '<ERROR: %s>' % msg
221 221 #raise # dbg
222 222 return out
223 223
224 224 class BasePrompt(object):
225 225 """Interactive prompt similar to Mathematica's."""
226 226
227 227 def _get_p_template(self):
228 228 return self._p_template
229 229
230 230 def _set_p_template(self,val):
231 231 self._p_template = val
232 232 self.set_p_str()
233 233
234 234 p_template = property(_get_p_template,_set_p_template,
235 235 doc='Template for prompt string creation')
236 236
237 237 def __init__(self,cache,sep,prompt,pad_left=False):
238 238
239 239 # Hack: we access information about the primary prompt through the
240 240 # cache argument. We need this, because we want the secondary prompt
241 241 # to be aligned with the primary one. Color table info is also shared
242 242 # by all prompt classes through the cache. Nice OO spaghetti code!
243 243 self.cache = cache
244 244 self.sep = sep
245 245
246 246 # regexp to count the number of spaces at the end of a prompt
247 247 # expression, useful for prompt auto-rewriting
248 248 self.rspace = re.compile(r'(\s*)$')
249 249 # Flag to left-pad prompt strings to match the length of the primary
250 250 # prompt
251 251 self.pad_left = pad_left
252 252
253 253 # Set template to create each actual prompt (where numbers change).
254 254 # Use a property
255 255 self.p_template = prompt
256 256 self.set_p_str()
257 257
258 258 def set_p_str(self):
259 259 """ Set the interpolating prompt strings.
260 260
261 261 This must be called every time the color settings change, because the
262 262 prompt_specials global may have changed."""
263 263
264 264 import os,time # needed in locals for prompt string handling
265 265 loc = locals()
266 266 try:
267 267 self.p_str = ItplNS('%s%s%s' %
268 268 ('${self.sep}${self.col_p}',
269 269 multiple_replace(prompt_specials, self.p_template),
270 270 '${self.col_norm}'),self.cache.user_ns,loc)
271 271
272 272 self.p_str_nocolor = ItplNS(multiple_replace(prompt_specials_nocolor,
273 273 self.p_template),
274 274 self.cache.user_ns,loc)
275 275 except:
276 276 print "Illegal prompt template (check $ usage!):",self.p_template
277 277 self.p_str = self.p_template
278 278 self.p_str_nocolor = self.p_template
279 279
280 280 def write(self,msg): # dbg
281 281 sys.stdout.write(msg)
282 282 return ''
283 283
284 284 def __str__(self):
285 285 """Return a string form of the prompt.
286 286
287 287 This for is useful for continuation and output prompts, since it is
288 288 left-padded to match lengths with the primary one (if the
289 289 self.pad_left attribute is set)."""
290 290
291 291 out_str = str_safe(self.p_str)
292 292 if self.pad_left:
293 293 # We must find the amount of padding required to match lengths,
294 294 # taking the color escapes (which are invisible on-screen) into
295 295 # account.
296 296 esc_pad = len(out_str) - len(str_safe(self.p_str_nocolor))
297 297 format = '%%%ss' % (len(str(self.cache.last_prompt))+esc_pad)
298 298 return format % out_str
299 299 else:
300 300 return out_str
301 301
302 302 # these path filters are put in as methods so that we can control the
303 303 # namespace where the prompt strings get evaluated
304 304 def cwd_filt(self,depth):
305 305 """Return the last depth elements of the current working directory.
306 306
307 307 $HOME is always replaced with '~'.
308 308 If depth==0, the full path is returned."""
309 309
310 310 cwd = os.getcwd().replace(HOME,"~")
311 311 out = os.sep.join(cwd.split(os.sep)[-depth:])
312 312 if out:
313 313 return out
314 314 else:
315 315 return os.sep
316 316
317 317 def cwd_filt2(self,depth):
318 318 """Return the last depth elements of the current working directory.
319 319
320 320 $HOME is always replaced with '~'.
321 321 If depth==0, the full path is returned."""
322 322
323 323 full_cwd = os.getcwd()
324 324 cwd = full_cwd.replace(HOME,"~").split(os.sep)
325 325 if '~' in cwd and len(cwd) == depth+1:
326 326 depth += 1
327 327 drivepart = ''
328 328 if sys.platform == 'win32' and len(cwd) > depth:
329 329 drivepart = os.path.splitdrive(full_cwd)[0]
330 330 out = drivepart + '/'.join(cwd[-depth:])
331 331
332 332 if out:
333 333 return out
334 334 else:
335 335 return os.sep
336 336
337 337 def __nonzero__(self):
338 338 """Implement boolean behavior.
339 339
340 340 Checks whether the p_str attribute is non-empty"""
341 341
342 342 return bool(self.p_template)
343 343
344 344 class Prompt1(BasePrompt):
345 345 """Input interactive prompt similar to Mathematica's."""
346 346
347 347 def __init__(self,cache,sep='\n',prompt='In [\\#]: ',pad_left=True):
348 348 BasePrompt.__init__(self,cache,sep,prompt,pad_left)
349 349
350 350 def set_colors(self):
351 351 self.set_p_str()
352 352 Colors = self.cache.color_table.active_colors # shorthand
353 353 self.col_p = Colors.in_prompt
354 354 self.col_num = Colors.in_number
355 355 self.col_norm = Colors.in_normal
356 356 # We need a non-input version of these escapes for the '--->'
357 357 # auto-call prompts used in the auto_rewrite() method.
358 358 self.col_p_ni = self.col_p.replace('\001','').replace('\002','')
359 359 self.col_norm_ni = Colors.normal
360 360
361 361 def __str__(self):
362 362 self.cache.prompt_count += 1
363 363 self.cache.last_prompt = str_safe(self.p_str_nocolor).split('\n')[-1]
364 364 return str_safe(self.p_str)
365 365
366 366 def auto_rewrite(self):
367 367 """Print a string of the form '--->' which lines up with the previous
368 368 input string. Useful for systems which re-write the user input when
369 369 handling automatically special syntaxes."""
370 370
371 371 curr = str(self.cache.last_prompt)
372 372 nrspaces = len(self.rspace.search(curr).group())
373 373 return '%s%s>%s%s' % (self.col_p_ni,'-'*(len(curr)-nrspaces-1),
374 374 ' '*nrspaces,self.col_norm_ni)
375 375
376 376 class PromptOut(BasePrompt):
377 377 """Output interactive prompt similar to Mathematica's."""
378 378
379 379 def __init__(self,cache,sep='',prompt='Out[\\#]: ',pad_left=True):
380 380 BasePrompt.__init__(self,cache,sep,prompt,pad_left)
381 381 if not self.p_template:
382 382 self.__str__ = lambda: ''
383 383
384 384 def set_colors(self):
385 385 self.set_p_str()
386 386 Colors = self.cache.color_table.active_colors # shorthand
387 387 self.col_p = Colors.out_prompt
388 388 self.col_num = Colors.out_number
389 389 self.col_norm = Colors.normal
390 390
391 391 class Prompt2(BasePrompt):
392 392 """Interactive continuation prompt."""
393 393
394 394 def __init__(self,cache,prompt=' .\\D.: ',pad_left=True):
395 395 self.cache = cache
396 396 self.p_template = prompt
397 397 self.pad_left = pad_left
398 398 self.set_p_str()
399 399
400 400 def set_p_str(self):
401 401 import os,time # needed in locals for prompt string handling
402 402 loc = locals()
403 403 self.p_str = ItplNS('%s%s%s' %
404 404 ('${self.col_p2}',
405 405 multiple_replace(prompt_specials, self.p_template),
406 406 '$self.col_norm'),
407 407 self.cache.user_ns,loc)
408 408 self.p_str_nocolor = ItplNS(multiple_replace(prompt_specials_nocolor,
409 409 self.p_template),
410 410 self.cache.user_ns,loc)
411 411
412 412 def set_colors(self):
413 413 self.set_p_str()
414 414 Colors = self.cache.color_table.active_colors
415 415 self.col_p2 = Colors.in_prompt2
416 416 self.col_norm = Colors.in_normal
417 417 # FIXME (2004-06-16) HACK: prevent crashes for users who haven't
418 418 # updated their prompt_in2 definitions. Remove eventually.
419 419 self.col_p = Colors.out_prompt
420 420 self.col_num = Colors.out_number
421 421
422 422
423 423 #-----------------------------------------------------------------------------
424 424 class CachedOutput:
425 425 """Class for printing output from calculations while keeping a cache of
426 426 reults. It dynamically creates global variables prefixed with _ which
427 427 contain these results.
428 428
429 429 Meant to be used as a sys.displayhook replacement, providing numbered
430 430 prompts and cache services.
431 431
432 432 Initialize with initial and final values for cache counter (this defines
433 433 the maximum size of the cache."""
434 434
435 435 def __init__(self,shell,cache_size,Pprint,
436 436 colors='NoColor',input_sep='\n',
437 437 output_sep='\n',output_sep2='',
438 438 ps1 = None, ps2 = None,ps_out = None,pad_left=True):
439 439
440 440 cache_size_min = 3
441 441 if cache_size <= 0:
442 442 self.do_full_cache = 0
443 443 cache_size = 0
444 444 elif cache_size < cache_size_min:
445 445 self.do_full_cache = 0
446 446 cache_size = 0
447 447 warn('caching was disabled (min value for cache size is %s).' %
448 448 cache_size_min,level=3)
449 449 else:
450 450 self.do_full_cache = 1
451 451
452 452 self.cache_size = cache_size
453 453 self.input_sep = input_sep
454 454
455 455 # we need a reference to the user-level namespace
456 456 self.shell = shell
457 457 self.user_ns = shell.user_ns
458 458 # and to the user's input
459 459 self.input_hist = shell.input_hist
460 460 # and to the user's logger, for logging output
461 461 self.logger = shell.logger
462 462
463 463 # Set input prompt strings and colors
464 464 if cache_size == 0:
465 465 if ps1.find('%n') > -1 or ps1.find(r'\#') > -1 \
466 466 or ps1.find(r'\N') > -1:
467 467 ps1 = '>>> '
468 468 if ps2.find('%n') > -1 or ps2.find(r'\#') > -1 \
469 469 or ps2.find(r'\N') > -1:
470 470 ps2 = '... '
471 471 self.ps1_str = self._set_prompt_str(ps1,'In [\\#]: ','>>> ')
472 472 self.ps2_str = self._set_prompt_str(ps2,' .\\D.: ','... ')
473 473 self.ps_out_str = self._set_prompt_str(ps_out,'Out[\\#]: ','')
474 474
475 475 self.color_table = PromptColors
476 476 self.prompt1 = Prompt1(self,sep=input_sep,prompt=self.ps1_str,
477 477 pad_left=pad_left)
478 478 self.prompt2 = Prompt2(self,prompt=self.ps2_str,pad_left=pad_left)
479 479 self.prompt_out = PromptOut(self,sep='',prompt=self.ps_out_str,
480 480 pad_left=pad_left)
481 481 self.set_colors(colors)
482 482
483 483 # other more normal stuff
484 484 # b/c each call to the In[] prompt raises it by 1, even the first.
485 485 self.prompt_count = 0
486 486 # Store the last prompt string each time, we need it for aligning
487 487 # continuation and auto-rewrite prompts
488 488 self.last_prompt = ''
489 489 self.Pprint = Pprint
490 490 self.output_sep = output_sep
491 491 self.output_sep2 = output_sep2
492 492 self._,self.__,self.___ = '','',''
493 493 self.pprint_types = map(type,[(),[],{}])
494 494
495 495 # these are deliberately global:
496 496 to_user_ns = {'_':self._,'__':self.__,'___':self.___}
497 497 self.user_ns.update(to_user_ns)
498 498
499 499 def _set_prompt_str(self,p_str,cache_def,no_cache_def):
500 500 if p_str is None:
501 501 if self.do_full_cache:
502 502 return cache_def
503 503 else:
504 504 return no_cache_def
505 505 else:
506 506 return p_str
507 507
508 508 def set_colors(self,colors):
509 509 """Set the active color scheme and configure colors for the three
510 510 prompt subsystems."""
511 511
512 512 # FIXME: the prompt_specials global should be gobbled inside this
513 513 # class instead. Do it when cleaning up the whole 3-prompt system.
514 514 global prompt_specials
515 515 if colors.lower()=='nocolor':
516 516 prompt_specials = prompt_specials_nocolor
517 517 else:
518 518 prompt_specials = prompt_specials_color
519 519
520 520 self.color_table.set_active_scheme(colors)
521 521 self.prompt1.set_colors()
522 522 self.prompt2.set_colors()
523 523 self.prompt_out.set_colors()
524 524
525 525 def __call__(self,arg=None):
526 526 """Printing with history cache management.
527 527
528 528 This is invoked everytime the interpreter needs to print, and is
529 529 activated by setting the variable sys.displayhook to it."""
530 530
531 531 # If something injected a '_' variable in __builtin__, delete
532 532 # ipython's automatic one so we don't clobber that. gettext() in
533 533 # particular uses _, so we need to stay away from it.
534 534 if '_' in __builtin__.__dict__:
535 535 try:
536 536 del self.user_ns['_']
537 537 except KeyError:
538 538 pass
539 539 if arg is not None:
540 cout_write = Term.cout.write # fast lookup
540 cout_write = IPython.utils.io.Term.cout.write # fast lookup
541 541 # first handle the cache and counters
542 542
543 543 # do not print output if input ends in ';'
544 544 try:
545 545 if self.input_hist[self.prompt_count].endswith(';\n'):
546 546 return
547 547 except IndexError:
548 548 # some uses of ipshellembed may fail here
549 549 pass
550 550 # don't use print, puts an extra space
551 551 cout_write(self.output_sep)
552 552 outprompt = self.shell.hooks.generate_output_prompt()
553 553 # print "Got prompt: ", outprompt
554 554 if self.do_full_cache:
555 555 cout_write(outprompt)
556 556
557 557 # and now call a possibly user-defined print mechanism. Note that
558 558 # self.display typically prints as a side-effect, we don't do any
559 559 # printing to stdout here.
560 560 try:
561 561 manipulated_val = self.display(arg)
562 562 except TypeError:
563 563 # If the user's display hook didn't return a string we can
564 564 # print, we're done. Happens commonly if they return None
565 565 cout_write('\n')
566 566 return
567 567
568 568 # user display hooks can change the variable to be stored in
569 569 # output history
570 570 if manipulated_val is not None:
571 571 arg = manipulated_val
572 572
573 573 # avoid recursive reference when displaying _oh/Out
574 574 if arg is not self.user_ns['_oh']:
575 575 self.update(arg)
576 576
577 577 if self.logger.log_output:
578 578 self.logger.log_write(repr(arg),'output')
579 579 cout_write(self.output_sep2)
580 Term.cout.flush()
580 IPython.utils.io.Term.cout.flush()
581 581
582 582 def _display(self,arg):
583 583 """Default printer method, uses pprint.
584 584
585 585 Do ip.set_hook("result_display", my_displayhook) for custom result
586 586 display, e.g. when your own objects need special formatting.
587 587 """
588 588 try:
589 589 return IPython.utils.generics.result_display(arg)
590 590 except TryNext:
591 591 return self.shell.hooks.result_display(arg)
592 592
593 593 # Assign the default display method:
594 594 display = _display
595 595
596 596 def update(self,arg):
597 597 #print '***cache_count', self.cache_count # dbg
598 598 if len(self.user_ns['_oh']) >= self.cache_size and self.do_full_cache:
599 599 warn('Output cache limit (currently '+
600 600 `self.cache_size`+' entries) hit.\n'
601 601 'Flushing cache and resetting history counter...\n'
602 602 'The only history variables available will be _,__,___ and _1\n'
603 603 'with the current result.')
604 604
605 605 self.flush()
606 606 # Don't overwrite '_' and friends if '_' is in __builtin__ (otherwise
607 607 # we cause buggy behavior for things like gettext).
608 608 if '_' not in __builtin__.__dict__:
609 609 self.___ = self.__
610 610 self.__ = self._
611 611 self._ = arg
612 612 self.user_ns.update({'_':self._,'__':self.__,'___':self.___})
613 613
614 614 # hackish access to top-level namespace to create _1,_2... dynamically
615 615 to_main = {}
616 616 if self.do_full_cache:
617 617 new_result = '_'+`self.prompt_count`
618 618 to_main[new_result] = arg
619 619 self.user_ns.update(to_main)
620 620 self.user_ns['_oh'][self.prompt_count] = arg
621 621
622 622 def flush(self):
623 623 if not self.do_full_cache:
624 624 raise ValueError,"You shouldn't have reached the cache flush "\
625 625 "if full caching is not enabled!"
626 626 # delete auto-generated vars from global namespace
627 627
628 628 for n in range(1,self.prompt_count + 1):
629 629 key = '_'+`n`
630 630 try:
631 631 del self.user_ns[key]
632 632 except: pass
633 633 self.user_ns['_oh'].clear()
634 634
635 635 if '_' not in __builtin__.__dict__:
636 636 self.user_ns.update({'_':None,'__':None, '___':None})
637 637 import gc
638 638 gc.collect() # xxx needed?
639 639
@@ -1,1104 +1,1107 b''
1 1 # -*- coding: utf-8 -*-
2 2 """
3 3 ultratb.py -- Spice up your tracebacks!
4 4
5 5 * ColorTB
6 6 I've always found it a bit hard to visually parse tracebacks in Python. The
7 7 ColorTB class is a solution to that problem. It colors the different parts of a
8 8 traceback in a manner similar to what you would expect from a syntax-highlighting
9 9 text editor.
10 10
11 11 Installation instructions for ColorTB:
12 12 import sys,ultratb
13 13 sys.excepthook = ultratb.ColorTB()
14 14
15 15 * VerboseTB
16 16 I've also included a port of Ka-Ping Yee's "cgitb.py" that produces all kinds
17 17 of useful info when a traceback occurs. Ping originally had it spit out HTML
18 18 and intended it for CGI programmers, but why should they have all the fun? I
19 19 altered it to spit out colored text to the terminal. It's a bit overwhelming,
20 20 but kind of neat, and maybe useful for long-running programs that you believe
21 21 are bug-free. If a crash *does* occur in that type of program you want details.
22 22 Give it a shot--you'll love it or you'll hate it.
23 23
24 24 Note:
25 25
26 26 The Verbose mode prints the variables currently visible where the exception
27 27 happened (shortening their strings if too long). This can potentially be
28 28 very slow, if you happen to have a huge data structure whose string
29 29 representation is complex to compute. Your computer may appear to freeze for
30 30 a while with cpu usage at 100%. If this occurs, you can cancel the traceback
31 31 with Ctrl-C (maybe hitting it more than once).
32 32
33 33 If you encounter this kind of situation often, you may want to use the
34 34 Verbose_novars mode instead of the regular Verbose, which avoids formatting
35 35 variables (but otherwise includes the information and context given by
36 36 Verbose).
37 37
38 38
39 39 Installation instructions for ColorTB:
40 40 import sys,ultratb
41 41 sys.excepthook = ultratb.VerboseTB()
42 42
43 43 Note: Much of the code in this module was lifted verbatim from the standard
44 44 library module 'traceback.py' and Ka-Ping Yee's 'cgitb.py'.
45 45
46 46 * Color schemes
47 47 The colors are defined in the class TBTools through the use of the
48 48 ColorSchemeTable class. Currently the following exist:
49 49
50 50 - NoColor: allows all of this module to be used in any terminal (the color
51 51 escapes are just dummy blank strings).
52 52
53 53 - Linux: is meant to look good in a terminal like the Linux console (black
54 54 or very dark background).
55 55
56 56 - LightBG: similar to Linux but swaps dark/light colors to be more readable
57 57 in light background terminals.
58 58
59 59 You can implement other color schemes easily, the syntax is fairly
60 60 self-explanatory. Please send back new schemes you develop to the author for
61 61 possible inclusion in future releases.
62 62 """
63 63
64 64 #*****************************************************************************
65 65 # Copyright (C) 2001 Nathaniel Gray <n8gray@caltech.edu>
66 66 # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu>
67 67 #
68 68 # Distributed under the terms of the BSD License. The full license is in
69 69 # the file COPYING, distributed as part of this software.
70 70 #*****************************************************************************
71 71
72 72 from __future__ import with_statement
73 73
74 74 import inspect
75 75 import keyword
76 76 import linecache
77 77 import os
78 78 import pydoc
79 79 import re
80 80 import string
81 81 import sys
82 82 import time
83 83 import tokenize
84 84 import traceback
85 85 import types
86 86
87 87 # For purposes of monkeypatching inspect to fix a bug in it.
88 88 from inspect import getsourcefile, getfile, getmodule,\
89 89 ismodule, isclass, ismethod, isfunction, istraceback, isframe, iscode
90 90
91 91 # IPython's own modules
92 92 # Modified pdb which doesn't damage IPython's readline handling
93 93 from IPython.utils import PyColorize
94 94 from IPython.core import debugger, ipapi
95 95 from IPython.core.display_trap import DisplayTrap
96 96 from IPython.core.excolors import exception_colors
97 97 from IPython.utils.data import uniq_stable
98 from IPython.utils.io import Term
98 import IPython.utils.io
99 99 from IPython.utils.warn import info, error
100 100
101 101 # Globals
102 102 # amount of space to put line numbers before verbose tracebacks
103 103 INDENT_SIZE = 8
104 104
105 105 # Default color scheme. This is used, for example, by the traceback
106 106 # formatter. When running in an actual IPython instance, the user's rc.colors
107 107 # value is used, but havinga module global makes this functionality available
108 108 # to users of ultratb who are NOT running inside ipython.
109 109 DEFAULT_SCHEME = 'NoColor'
110 110
111 111 #---------------------------------------------------------------------------
112 112 # Code begins
113 113
114 114 # Utility functions
115 115 def inspect_error():
116 116 """Print a message about internal inspect errors.
117 117
118 118 These are unfortunately quite common."""
119 119
120 120 error('Internal Python error in the inspect module.\n'
121 121 'Below is the traceback from this internal error.\n')
122 122
123 123
124 124 def findsource(object):
125 125 """Return the entire source file and starting line number for an object.
126 126
127 127 The argument may be a module, class, method, function, traceback, frame,
128 128 or code object. The source code is returned as a list of all the lines
129 129 in the file and the line number indexes a line in that list. An IOError
130 130 is raised if the source code cannot be retrieved.
131 131
132 132 FIXED version with which we monkeypatch the stdlib to work around a bug."""
133 133
134 134 file = getsourcefile(object) or getfile(object)
135 135 # If the object is a frame, then trying to get the globals dict from its
136 136 # module won't work. Instead, the frame object itself has the globals
137 137 # dictionary.
138 138 globals_dict = None
139 139 if inspect.isframe(object):
140 140 # XXX: can this ever be false?
141 141 globals_dict = object.f_globals
142 142 else:
143 143 module = getmodule(object, file)
144 144 if module:
145 145 globals_dict = module.__dict__
146 146 lines = linecache.getlines(file, globals_dict)
147 147 if not lines:
148 148 raise IOError('could not get source code')
149 149
150 150 if ismodule(object):
151 151 return lines, 0
152 152
153 153 if isclass(object):
154 154 name = object.__name__
155 155 pat = re.compile(r'^(\s*)class\s*' + name + r'\b')
156 156 # make some effort to find the best matching class definition:
157 157 # use the one with the least indentation, which is the one
158 158 # that's most probably not inside a function definition.
159 159 candidates = []
160 160 for i in range(len(lines)):
161 161 match = pat.match(lines[i])
162 162 if match:
163 163 # if it's at toplevel, it's already the best one
164 164 if lines[i][0] == 'c':
165 165 return lines, i
166 166 # else add whitespace to candidate list
167 167 candidates.append((match.group(1), i))
168 168 if candidates:
169 169 # this will sort by whitespace, and by line number,
170 170 # less whitespace first
171 171 candidates.sort()
172 172 return lines, candidates[0][1]
173 173 else:
174 174 raise IOError('could not find class definition')
175 175
176 176 if ismethod(object):
177 177 object = object.im_func
178 178 if isfunction(object):
179 179 object = object.func_code
180 180 if istraceback(object):
181 181 object = object.tb_frame
182 182 if isframe(object):
183 183 object = object.f_code
184 184 if iscode(object):
185 185 if not hasattr(object, 'co_firstlineno'):
186 186 raise IOError('could not find function definition')
187 187 pat = re.compile(r'^(\s*def\s)|(.*(?<!\w)lambda(:|\s))|^(\s*@)')
188 188 pmatch = pat.match
189 189 # fperez - fix: sometimes, co_firstlineno can give a number larger than
190 190 # the length of lines, which causes an error. Safeguard against that.
191 191 lnum = min(object.co_firstlineno,len(lines))-1
192 192 while lnum > 0:
193 193 if pmatch(lines[lnum]): break
194 194 lnum -= 1
195 195
196 196 return lines, lnum
197 197 raise IOError('could not find code object')
198 198
199 199 # Monkeypatch inspect to apply our bugfix. This code only works with py25
200 200 if sys.version_info[:2] >= (2,5):
201 201 inspect.findsource = findsource
202 202
203 203 def fix_frame_records_filenames(records):
204 204 """Try to fix the filenames in each record from inspect.getinnerframes().
205 205
206 206 Particularly, modules loaded from within zip files have useless filenames
207 207 attached to their code object, and inspect.getinnerframes() just uses it.
208 208 """
209 209 fixed_records = []
210 210 for frame, filename, line_no, func_name, lines, index in records:
211 211 # Look inside the frame's globals dictionary for __file__, which should
212 212 # be better.
213 213 better_fn = frame.f_globals.get('__file__', None)
214 214 if isinstance(better_fn, str):
215 215 # Check the type just in case someone did something weird with
216 216 # __file__. It might also be None if the error occurred during
217 217 # import.
218 218 filename = better_fn
219 219 fixed_records.append((frame, filename, line_no, func_name, lines, index))
220 220 return fixed_records
221 221
222 222
223 223 def _fixed_getinnerframes(etb, context=1,tb_offset=0):
224 224 import linecache
225 225 LNUM_POS, LINES_POS, INDEX_POS = 2, 4, 5
226 226
227 227 records = fix_frame_records_filenames(inspect.getinnerframes(etb, context))
228 228
229 229 # If the error is at the console, don't build any context, since it would
230 230 # otherwise produce 5 blank lines printed out (there is no file at the
231 231 # console)
232 232 rec_check = records[tb_offset:]
233 233 try:
234 234 rname = rec_check[0][1]
235 235 if rname == '<ipython console>' or rname.endswith('<string>'):
236 236 return rec_check
237 237 except IndexError:
238 238 pass
239 239
240 240 aux = traceback.extract_tb(etb)
241 241 assert len(records) == len(aux)
242 242 for i, (file, lnum, _, _) in zip(range(len(records)), aux):
243 243 maybeStart = lnum-1 - context//2
244 244 start = max(maybeStart, 0)
245 245 end = start + context
246 246 lines = linecache.getlines(file)[start:end]
247 247 # pad with empty lines if necessary
248 248 if maybeStart < 0:
249 249 lines = (['\n'] * -maybeStart) + lines
250 250 if len(lines) < context:
251 251 lines += ['\n'] * (context - len(lines))
252 252 buf = list(records[i])
253 253 buf[LNUM_POS] = lnum
254 254 buf[INDEX_POS] = lnum - 1 - start
255 255 buf[LINES_POS] = lines
256 256 records[i] = tuple(buf)
257 257 return records[tb_offset:]
258 258
259 259 # Helper function -- largely belongs to VerboseTB, but we need the same
260 260 # functionality to produce a pseudo verbose TB for SyntaxErrors, so that they
261 261 # can be recognized properly by ipython.el's py-traceback-line-re
262 262 # (SyntaxErrors have to be treated specially because they have no traceback)
263 263
264 264 _parser = PyColorize.Parser()
265 265
266 266 def _format_traceback_lines(lnum, index, lines, Colors, lvals=None,scheme=None):
267 267 numbers_width = INDENT_SIZE - 1
268 268 res = []
269 269 i = lnum - index
270 270
271 271 # This lets us get fully syntax-highlighted tracebacks.
272 272 if scheme is None:
273 273 ipinst = ipapi.get()
274 274 if ipinst is not None:
275 275 scheme = ipinst.colors
276 276 else:
277 277 scheme = DEFAULT_SCHEME
278 278
279 279 _line_format = _parser.format2
280 280
281 281 for line in lines:
282 282 new_line, err = _line_format(line,'str',scheme)
283 283 if not err: line = new_line
284 284
285 285 if i == lnum:
286 286 # This is the line with the error
287 287 pad = numbers_width - len(str(i))
288 288 if pad >= 3:
289 289 marker = '-'*(pad-3) + '-> '
290 290 elif pad == 2:
291 291 marker = '> '
292 292 elif pad == 1:
293 293 marker = '>'
294 294 else:
295 295 marker = ''
296 296 num = marker + str(i)
297 297 line = '%s%s%s %s%s' %(Colors.linenoEm, num,
298 298 Colors.line, line, Colors.Normal)
299 299 else:
300 300 num = '%*s' % (numbers_width,i)
301 301 line = '%s%s%s %s' %(Colors.lineno, num,
302 302 Colors.Normal, line)
303 303
304 304 res.append(line)
305 305 if lvals and i == lnum:
306 306 res.append(lvals + '\n')
307 307 i = i + 1
308 308 return res
309 309
310 310
311 311 #---------------------------------------------------------------------------
312 312 # Module classes
313 313 class TBTools:
314 314 """Basic tools used by all traceback printer classes."""
315 315
316 #: Default output stream, can be overridden at call time. A special value
317 #: of 'stdout' *as a string* can be given to force extraction of sys.stdout
318 #: at runtime. This allows testing exception printing with doctests, that
319 #: swap sys.stdout just at execution time.
320 #: Warning: be VERY careful to set this to one of the Term streams, NEVER
321 #: directly to sys.stdout/err, because under win32 the Term streams come from
322 #: pyreadline and know how to handle color correctly, whie stdout/err don't.
323 out_stream = Term.cerr
316 # This attribute us used in globalipapp.py to have stdout used for
317 # writting exceptions. This is needed so nose can trap them. This attribute
318 # should be None (the default, which will use IPython.utils.io.Term) or
319 # the string 'stdout' which will cause the override to sys.stdout.
320 out_stream = None
324 321
325 322 def __init__(self,color_scheme = 'NoColor',call_pdb=False):
326 323 # Whether to call the interactive pdb debugger after printing
327 324 # tracebacks or not
328 325 self.call_pdb = call_pdb
329 326
330 327 # Create color table
331 328 self.color_scheme_table = exception_colors()
332 329
333 330 self.set_colors(color_scheme)
334 331 self.old_scheme = color_scheme # save initial value for toggles
335 332
336 333 if call_pdb:
337 334 self.pdb = debugger.Pdb(self.color_scheme_table.active_scheme_name)
338 335 else:
339 336 self.pdb = None
340 337
341 338 def set_colors(self,*args,**kw):
342 339 """Shorthand access to the color table scheme selector method."""
343 340
344 341 # Set own color table
345 342 self.color_scheme_table.set_active_scheme(*args,**kw)
346 343 # for convenience, set Colors to the active scheme
347 344 self.Colors = self.color_scheme_table.active_colors
348 345 # Also set colors of debugger
349 346 if hasattr(self,'pdb') and self.pdb is not None:
350 347 self.pdb.set_colors(*args,**kw)
351 348
352 349 def color_toggle(self):
353 350 """Toggle between the currently active color scheme and NoColor."""
354 351
355 352 if self.color_scheme_table.active_scheme_name == 'NoColor':
356 353 self.color_scheme_table.set_active_scheme(self.old_scheme)
357 354 self.Colors = self.color_scheme_table.active_colors
358 355 else:
359 356 self.old_scheme = self.color_scheme_table.active_scheme_name
360 357 self.color_scheme_table.set_active_scheme('NoColor')
361 358 self.Colors = self.color_scheme_table.active_colors
362 359
363 360 #---------------------------------------------------------------------------
364 361 class ListTB(TBTools):
365 362 """Print traceback information from a traceback list, with optional color.
366 363
367 364 Calling: requires 3 arguments:
368 365 (etype, evalue, elist)
369 366 as would be obtained by:
370 367 etype, evalue, tb = sys.exc_info()
371 368 if tb:
372 369 elist = traceback.extract_tb(tb)
373 370 else:
374 371 elist = None
375 372
376 373 It can thus be used by programs which need to process the traceback before
377 374 printing (such as console replacements based on the code module from the
378 375 standard library).
379 376
380 377 Because they are meant to be called without a full traceback (only a
381 378 list), instances of this class can't call the interactive pdb debugger."""
382 379
383 380 def __init__(self,color_scheme = 'NoColor'):
384 381 TBTools.__init__(self,color_scheme = color_scheme,call_pdb=0)
385 382
386 383 def __call__(self, etype, value, elist):
387 Term.cout.flush()
388 Term.cerr.write(self.text(etype,value,elist))
389 Term.cerr.write('\n')
384 IPython.utils.io.Term.cout.flush()
385 IPython.utils.io.Term.cerr.write(self.text(etype,value,elist))
386 IPython.utils.io.Term.cerr.write('\n')
390 387
391 388 def text(self, etype, value, elist, context=5):
392 389 """Return a color formatted string with the traceback info.
393 390
394 391 Parameters
395 392 ----------
396 393 etype : exception type
397 394 Type of the exception raised.
398 395
399 396 value : object
400 397 Data stored in the exception
401 398
402 399 elist : list
403 400 List of frames, see class docstring for details.
404 401
405 402 Returns
406 403 -------
407 404 String with formatted exception.
408 405 """
409 406
410 407 Colors = self.Colors
411 408 out_string = []
412 409 if elist:
413 410 out_string.append('Traceback %s(most recent call last)%s:' %
414 411 (Colors.normalEm, Colors.Normal) + '\n')
415 412 out_string.extend(self._format_list(elist))
416 413 lines = self._format_exception_only(etype, value)
417 414 for line in lines[:-1]:
418 415 out_string.append(" "+line)
419 416 out_string.append(lines[-1])
420 417 return ''.join(out_string)
421 418
422 419 def _format_list(self, extracted_list):
423 420 """Format a list of traceback entry tuples for printing.
424 421
425 422 Given a list of tuples as returned by extract_tb() or
426 423 extract_stack(), return a list of strings ready for printing.
427 424 Each string in the resulting list corresponds to the item with the
428 425 same index in the argument list. Each string ends in a newline;
429 426 the strings may contain internal newlines as well, for those items
430 427 whose source text line is not None.
431 428
432 429 Lifted almost verbatim from traceback.py
433 430 """
434 431
435 432 Colors = self.Colors
436 433 list = []
437 434 for filename, lineno, name, line in extracted_list[:-1]:
438 435 item = ' File %s"%s"%s, line %s%d%s, in %s%s%s\n' % \
439 436 (Colors.filename, filename, Colors.Normal,
440 437 Colors.lineno, lineno, Colors.Normal,
441 438 Colors.name, name, Colors.Normal)
442 439 if line:
443 440 item = item + ' %s\n' % line.strip()
444 441 list.append(item)
445 442 # Emphasize the last entry
446 443 filename, lineno, name, line = extracted_list[-1]
447 444 item = '%s File %s"%s"%s, line %s%d%s, in %s%s%s%s\n' % \
448 445 (Colors.normalEm,
449 446 Colors.filenameEm, filename, Colors.normalEm,
450 447 Colors.linenoEm, lineno, Colors.normalEm,
451 448 Colors.nameEm, name, Colors.normalEm,
452 449 Colors.Normal)
453 450 if line:
454 451 item = item + '%s %s%s\n' % (Colors.line, line.strip(),
455 452 Colors.Normal)
456 453 list.append(item)
457 454 return list
458 455
459 456 def _format_exception_only(self, etype, value):
460 457 """Format the exception part of a traceback.
461 458
462 459 The arguments are the exception type and value such as given by
463 460 sys.exc_info()[:2]. The return value is a list of strings, each ending
464 461 in a newline. Normally, the list contains a single string; however,
465 462 for SyntaxError exceptions, it contains several lines that (when
466 463 printed) display detailed information about where the syntax error
467 464 occurred. The message indicating which exception occurred is the
468 465 always last string in the list.
469 466
470 467 Also lifted nearly verbatim from traceback.py
471 468 """
472 469
473 470 have_filedata = False
474 471 Colors = self.Colors
475 472 list = []
476 473 try:
477 474 stype = Colors.excName + etype.__name__ + Colors.Normal
478 475 except AttributeError:
479 476 stype = etype # String exceptions don't get special coloring
480 477 if value is None:
481 478 list.append( str(stype) + '\n')
482 479 else:
483 480 if etype is SyntaxError:
484 481 try:
485 482 msg, (filename, lineno, offset, line) = value
486 483 except:
487 484 have_filedata = False
488 485 else:
489 486 have_filedata = True
490 487 #print 'filename is',filename # dbg
491 488 if not filename: filename = "<string>"
492 489 list.append('%s File %s"%s"%s, line %s%d%s\n' % \
493 490 (Colors.normalEm,
494 491 Colors.filenameEm, filename, Colors.normalEm,
495 492 Colors.linenoEm, lineno, Colors.Normal ))
496 493 if line is not None:
497 494 i = 0
498 495 while i < len(line) and line[i].isspace():
499 496 i = i+1
500 497 list.append('%s %s%s\n' % (Colors.line,
501 498 line.strip(),
502 499 Colors.Normal))
503 500 if offset is not None:
504 501 s = ' '
505 502 for c in line[i:offset-1]:
506 503 if c.isspace():
507 504 s = s + c
508 505 else:
509 506 s = s + ' '
510 507 list.append('%s%s^%s\n' % (Colors.caret, s,
511 508 Colors.Normal) )
512 509 value = msg
513 510 s = self._some_str(value)
514 511 if s:
515 512 list.append('%s%s:%s %s\n' % (str(stype), Colors.excName,
516 513 Colors.Normal, s))
517 514 else:
518 515 list.append('%s\n' % str(stype))
519 516
520 517 # sync with user hooks
521 518 if have_filedata:
522 519 ipinst = ipapi.get()
523 520 if ipinst is not None:
524 521 ipinst.hooks.synchronize_with_editor(filename, lineno, 0)
525 522
526 523 return list
527 524
528 525 def show_exception_only(self, etype, value):
529 526 """Only print the exception type and message, without a traceback.
530 527
531 528 Parameters
532 529 ----------
533 530 etype : exception type
534 531 value : exception value
535 532 """
536 533 # This method needs to use __call__ from *this* class, not the one from
537 534 # a subclass whose signature or behavior may be different
538 Term.cout.flush()
539 ostream = sys.stdout if self.out_stream == 'stdout' else Term.cerr
535 if self.out_stream == 'stdout':
536 ostream = sys.stdout
537 else:
538 ostream = IPython.utils.io.Term.cerr
539 ostream.flush()
540 540 ostream.write(ListTB.text(self, etype, value, []))
541 ostream.flush()
541 ostream.flush()
542 542
543 543 def _some_str(self, value):
544 544 # Lifted from traceback.py
545 545 try:
546 546 return str(value)
547 547 except:
548 548 return '<unprintable %s object>' % type(value).__name__
549 549
550 550 #----------------------------------------------------------------------------
551 551 class VerboseTB(TBTools):
552 552 """A port of Ka-Ping Yee's cgitb.py module that outputs color text instead
553 553 of HTML. Requires inspect and pydoc. Crazy, man.
554 554
555 555 Modified version which optionally strips the topmost entries from the
556 556 traceback, to be used with alternate interpreters (because their own code
557 557 would appear in the traceback)."""
558 558
559 559 def __init__(self,color_scheme = 'Linux',tb_offset=0,long_header=0,
560 560 call_pdb = 0, include_vars=1):
561 561 """Specify traceback offset, headers and color scheme.
562 562
563 563 Define how many frames to drop from the tracebacks. Calling it with
564 564 tb_offset=1 allows use of this handler in interpreters which will have
565 565 their own code at the top of the traceback (VerboseTB will first
566 566 remove that frame before printing the traceback info)."""
567 567 TBTools.__init__(self,color_scheme=color_scheme,call_pdb=call_pdb)
568 568 self.tb_offset = tb_offset
569 569 self.long_header = long_header
570 570 self.include_vars = include_vars
571 571
572 572 def text(self, etype, evalue, etb, context=5):
573 573 """Return a nice text document describing the traceback."""
574 574
575 575 # some locals
576 576 try:
577 577 etype = etype.__name__
578 578 except AttributeError:
579 579 pass
580 580 Colors = self.Colors # just a shorthand + quicker name lookup
581 581 ColorsNormal = Colors.Normal # used a lot
582 582 col_scheme = self.color_scheme_table.active_scheme_name
583 583 indent = ' '*INDENT_SIZE
584 584 em_normal = '%s\n%s%s' % (Colors.valEm, indent,ColorsNormal)
585 585 undefined = '%sundefined%s' % (Colors.em, ColorsNormal)
586 586 exc = '%s%s%s' % (Colors.excName,etype,ColorsNormal)
587 587
588 588 # some internal-use functions
589 589 def text_repr(value):
590 590 """Hopefully pretty robust repr equivalent."""
591 591 # this is pretty horrible but should always return *something*
592 592 try:
593 593 return pydoc.text.repr(value)
594 594 except KeyboardInterrupt:
595 595 raise
596 596 except:
597 597 try:
598 598 return repr(value)
599 599 except KeyboardInterrupt:
600 600 raise
601 601 except:
602 602 try:
603 603 # all still in an except block so we catch
604 604 # getattr raising
605 605 name = getattr(value, '__name__', None)
606 606 if name:
607 607 # ick, recursion
608 608 return text_repr(name)
609 609 klass = getattr(value, '__class__', None)
610 610 if klass:
611 611 return '%s instance' % text_repr(klass)
612 612 except KeyboardInterrupt:
613 613 raise
614 614 except:
615 615 return 'UNRECOVERABLE REPR FAILURE'
616 616 def eqrepr(value, repr=text_repr): return '=%s' % repr(value)
617 617 def nullrepr(value, repr=text_repr): return ''
618 618
619 619 # meat of the code begins
620 620 try:
621 621 etype = etype.__name__
622 622 except AttributeError:
623 623 pass
624 624
625 625 if self.long_header:
626 626 # Header with the exception type, python version, and date
627 627 pyver = 'Python ' + string.split(sys.version)[0] + ': ' + sys.executable
628 628 date = time.ctime(time.time())
629 629
630 630 head = '%s%s%s\n%s%s%s\n%s' % (Colors.topline, '-'*75, ColorsNormal,
631 631 exc, ' '*(75-len(str(etype))-len(pyver)),
632 632 pyver, string.rjust(date, 75) )
633 633 head += "\nA problem occured executing Python code. Here is the sequence of function"\
634 634 "\ncalls leading up to the error, with the most recent (innermost) call last."
635 635 else:
636 636 # Simplified header
637 637 head = '%s%s%s\n%s%s' % (Colors.topline, '-'*75, ColorsNormal,exc,
638 638 string.rjust('Traceback (most recent call last)',
639 639 75 - len(str(etype)) ) )
640 640 frames = []
641 641 # Flush cache before calling inspect. This helps alleviate some of the
642 642 # problems with python 2.3's inspect.py.
643 643 linecache.checkcache()
644 644 # Drop topmost frames if requested
645 645 try:
646 646 # Try the default getinnerframes and Alex's: Alex's fixes some
647 647 # problems, but it generates empty tracebacks for console errors
648 648 # (5 blanks lines) where none should be returned.
649 649 #records = inspect.getinnerframes(etb, context)[self.tb_offset:]
650 650 #print 'python records:', records # dbg
651 651 records = _fixed_getinnerframes(etb, context,self.tb_offset)
652 652 #print 'alex records:', records # dbg
653 653 except:
654 654
655 655 # FIXME: I've been getting many crash reports from python 2.3
656 656 # users, traceable to inspect.py. If I can find a small test-case
657 657 # to reproduce this, I should either write a better workaround or
658 658 # file a bug report against inspect (if that's the real problem).
659 659 # So far, I haven't been able to find an isolated example to
660 660 # reproduce the problem.
661 661 inspect_error()
662 traceback.print_exc(file=Term.cerr)
662 traceback.print_exc(file=IPython.utils.io.Term.cerr)
663 663 info('\nUnfortunately, your original traceback can not be constructed.\n')
664 664 return ''
665 665
666 666 # build some color string templates outside these nested loops
667 667 tpl_link = '%s%%s%s' % (Colors.filenameEm,ColorsNormal)
668 668 tpl_call = 'in %s%%s%s%%s%s' % (Colors.vName, Colors.valEm,
669 669 ColorsNormal)
670 670 tpl_call_fail = 'in %s%%s%s(***failed resolving arguments***)%s' % \
671 671 (Colors.vName, Colors.valEm, ColorsNormal)
672 672 tpl_local_var = '%s%%s%s' % (Colors.vName, ColorsNormal)
673 673 tpl_global_var = '%sglobal%s %s%%s%s' % (Colors.em, ColorsNormal,
674 674 Colors.vName, ColorsNormal)
675 675 tpl_name_val = '%%s %s= %%s%s' % (Colors.valEm, ColorsNormal)
676 676 tpl_line = '%s%%s%s %%s' % (Colors.lineno, ColorsNormal)
677 677 tpl_line_em = '%s%%s%s %%s%s' % (Colors.linenoEm,Colors.line,
678 678 ColorsNormal)
679 679
680 680 # now, loop over all records printing context and info
681 681 abspath = os.path.abspath
682 682 for frame, file, lnum, func, lines, index in records:
683 683 #print '*** record:',file,lnum,func,lines,index # dbg
684 684 try:
685 685 file = file and abspath(file) or '?'
686 686 except OSError:
687 687 # if file is '<console>' or something not in the filesystem,
688 688 # the abspath call will throw an OSError. Just ignore it and
689 689 # keep the original file string.
690 690 pass
691 691 link = tpl_link % file
692 692 try:
693 693 args, varargs, varkw, locals = inspect.getargvalues(frame)
694 694 except:
695 695 # This can happen due to a bug in python2.3. We should be
696 696 # able to remove this try/except when 2.4 becomes a
697 697 # requirement. Bug details at http://python.org/sf/1005466
698 698 inspect_error()
699 traceback.print_exc(file=Term.cerr)
699 traceback.print_exc(file=IPython.utils.io.Term.cerr)
700 700 info("\nIPython's exception reporting continues...\n")
701 701
702 702 if func == '?':
703 703 call = ''
704 704 else:
705 705 # Decide whether to include variable details or not
706 706 var_repr = self.include_vars and eqrepr or nullrepr
707 707 try:
708 708 call = tpl_call % (func,inspect.formatargvalues(args,
709 709 varargs, varkw,
710 710 locals,formatvalue=var_repr))
711 711 except KeyError:
712 712 # Very odd crash from inspect.formatargvalues(). The
713 713 # scenario under which it appeared was a call to
714 714 # view(array,scale) in NumTut.view.view(), where scale had
715 715 # been defined as a scalar (it should be a tuple). Somehow
716 716 # inspect messes up resolving the argument list of view()
717 717 # and barfs out. At some point I should dig into this one
718 718 # and file a bug report about it.
719 719 inspect_error()
720 traceback.print_exc(file=Term.cerr)
720 traceback.print_exc(file=IPython.utils.io.Term.cerr)
721 721 info("\nIPython's exception reporting continues...\n")
722 722 call = tpl_call_fail % func
723 723
724 724 # Initialize a list of names on the current line, which the
725 725 # tokenizer below will populate.
726 726 names = []
727 727
728 728 def tokeneater(token_type, token, start, end, line):
729 729 """Stateful tokeneater which builds dotted names.
730 730
731 731 The list of names it appends to (from the enclosing scope) can
732 732 contain repeated composite names. This is unavoidable, since
733 733 there is no way to disambguate partial dotted structures until
734 734 the full list is known. The caller is responsible for pruning
735 735 the final list of duplicates before using it."""
736 736
737 737 # build composite names
738 738 if token == '.':
739 739 try:
740 740 names[-1] += '.'
741 741 # store state so the next token is added for x.y.z names
742 742 tokeneater.name_cont = True
743 743 return
744 744 except IndexError:
745 745 pass
746 746 if token_type == tokenize.NAME and token not in keyword.kwlist:
747 747 if tokeneater.name_cont:
748 748 # Dotted names
749 749 names[-1] += token
750 750 tokeneater.name_cont = False
751 751 else:
752 752 # Regular new names. We append everything, the caller
753 753 # will be responsible for pruning the list later. It's
754 754 # very tricky to try to prune as we go, b/c composite
755 755 # names can fool us. The pruning at the end is easy
756 756 # to do (or the caller can print a list with repeated
757 757 # names if so desired.
758 758 names.append(token)
759 759 elif token_type == tokenize.NEWLINE:
760 760 raise IndexError
761 761 # we need to store a bit of state in the tokenizer to build
762 762 # dotted names
763 763 tokeneater.name_cont = False
764 764
765 765 def linereader(file=file, lnum=[lnum], getline=linecache.getline):
766 766 line = getline(file, lnum[0])
767 767 lnum[0] += 1
768 768 return line
769 769
770 770 # Build the list of names on this line of code where the exception
771 771 # occurred.
772 772 try:
773 773 # This builds the names list in-place by capturing it from the
774 774 # enclosing scope.
775 775 tokenize.tokenize(linereader, tokeneater)
776 776 except IndexError:
777 777 # signals exit of tokenizer
778 778 pass
779 779 except tokenize.TokenError,msg:
780 780 _m = ("An unexpected error occurred while tokenizing input\n"
781 781 "The following traceback may be corrupted or invalid\n"
782 782 "The error message is: %s\n" % msg)
783 783 error(_m)
784 784
785 785 # prune names list of duplicates, but keep the right order
786 786 unique_names = uniq_stable(names)
787 787
788 788 # Start loop over vars
789 789 lvals = []
790 790 if self.include_vars:
791 791 for name_full in unique_names:
792 792 name_base = name_full.split('.',1)[0]
793 793 if name_base in frame.f_code.co_varnames:
794 794 if locals.has_key(name_base):
795 795 try:
796 796 value = repr(eval(name_full,locals))
797 797 except:
798 798 value = undefined
799 799 else:
800 800 value = undefined
801 801 name = tpl_local_var % name_full
802 802 else:
803 803 if frame.f_globals.has_key(name_base):
804 804 try:
805 805 value = repr(eval(name_full,frame.f_globals))
806 806 except:
807 807 value = undefined
808 808 else:
809 809 value = undefined
810 810 name = tpl_global_var % name_full
811 811 lvals.append(tpl_name_val % (name,value))
812 812 if lvals:
813 813 lvals = '%s%s' % (indent,em_normal.join(lvals))
814 814 else:
815 815 lvals = ''
816 816
817 817 level = '%s %s\n' % (link,call)
818 818
819 819 if index is None:
820 820 frames.append(level)
821 821 else:
822 822 frames.append('%s%s' % (level,''.join(
823 823 _format_traceback_lines(lnum,index,lines,Colors,lvals,
824 824 col_scheme))))
825 825
826 826 # Get (safely) a string form of the exception info
827 827 try:
828 828 etype_str,evalue_str = map(str,(etype,evalue))
829 829 except:
830 830 # User exception is improperly defined.
831 831 etype,evalue = str,sys.exc_info()[:2]
832 832 etype_str,evalue_str = map(str,(etype,evalue))
833 833 # ... and format it
834 834 exception = ['%s%s%s: %s' % (Colors.excName, etype_str,
835 835 ColorsNormal, evalue_str)]
836 836 if type(evalue) is types.InstanceType:
837 837 try:
838 838 names = [w for w in dir(evalue) if isinstance(w, basestring)]
839 839 except:
840 840 # Every now and then, an object with funny inernals blows up
841 841 # when dir() is called on it. We do the best we can to report
842 842 # the problem and continue
843 843 _m = '%sException reporting error (object with broken dir())%s:'
844 844 exception.append(_m % (Colors.excName,ColorsNormal))
845 845 etype_str,evalue_str = map(str,sys.exc_info()[:2])
846 846 exception.append('%s%s%s: %s' % (Colors.excName,etype_str,
847 847 ColorsNormal, evalue_str))
848 848 names = []
849 849 for name in names:
850 850 value = text_repr(getattr(evalue, name))
851 851 exception.append('\n%s%s = %s' % (indent, name, value))
852 852
853 853 # vds: >>
854 854 if records:
855 855 filepath, lnum = records[-1][1:3]
856 856 #print "file:", str(file), "linenb", str(lnum) # dbg
857 857 filepath = os.path.abspath(filepath)
858 858 ipinst = ipapi.get()
859 859 if ipinst is not None:
860 860 ipinst.hooks.synchronize_with_editor(filepath, lnum, 0)
861 861 # vds: <<
862 862
863 863 # return all our info assembled as a single string
864 864 return '%s\n\n%s\n%s' % (head,'\n'.join(frames),''.join(exception[0]) )
865 865
866 866 def debugger(self,force=False):
867 867 """Call up the pdb debugger if desired, always clean up the tb
868 868 reference.
869 869
870 870 Keywords:
871 871
872 872 - force(False): by default, this routine checks the instance call_pdb
873 873 flag and does not actually invoke the debugger if the flag is false.
874 874 The 'force' option forces the debugger to activate even if the flag
875 875 is false.
876 876
877 877 If the call_pdb flag is set, the pdb interactive debugger is
878 878 invoked. In all cases, the self.tb reference to the current traceback
879 879 is deleted to prevent lingering references which hamper memory
880 880 management.
881 881
882 882 Note that each call to pdb() does an 'import readline', so if your app
883 883 requires a special setup for the readline completers, you'll have to
884 884 fix that by hand after invoking the exception handler."""
885 885
886 886 if force or self.call_pdb:
887 887 if self.pdb is None:
888 888 self.pdb = debugger.Pdb(
889 889 self.color_scheme_table.active_scheme_name)
890 890 # the system displayhook may have changed, restore the original
891 891 # for pdb
892 892 display_trap = DisplayTrap(None, sys.__displayhook__)
893 893 with display_trap:
894 894 self.pdb.reset()
895 895 # Find the right frame so we don't pop up inside ipython itself
896 896 if hasattr(self,'tb') and self.tb is not None:
897 897 etb = self.tb
898 898 else:
899 899 etb = self.tb = sys.last_traceback
900 900 while self.tb is not None and self.tb.tb_next is not None:
901 901 self.tb = self.tb.tb_next
902 902 if etb and etb.tb_next:
903 903 etb = etb.tb_next
904 904 self.pdb.botframe = etb.tb_frame
905 905 self.pdb.interaction(self.tb.tb_frame, self.tb)
906 906
907 907 if hasattr(self,'tb'):
908 908 del self.tb
909 909
910 910 def handler(self, info=None):
911 911 (etype, evalue, etb) = info or sys.exc_info()
912 912 self.tb = etb
913 Term.cout.flush()
914 Term.cerr.write(self.text(etype, evalue, etb))
915 Term.cerr.write('\n')
913 IPython.utils.io.Term.cout.flush()
914 IPython.utils.io.Term.cerr.write(self.text(etype, evalue, etb))
915 IPython.utils.io.Term.cerr.write('\n')
916 916
917 917 # Changed so an instance can just be called as VerboseTB_inst() and print
918 918 # out the right info on its own.
919 919 def __call__(self, etype=None, evalue=None, etb=None):
920 920 """This hook can replace sys.excepthook (for Python 2.1 or higher)."""
921 921 if etb is None:
922 922 self.handler()
923 923 else:
924 924 self.handler((etype, evalue, etb))
925 925 try:
926 926 self.debugger()
927 927 except KeyboardInterrupt:
928 928 print "\nKeyboardInterrupt"
929 929
930 930 #----------------------------------------------------------------------------
931 931 class FormattedTB(VerboseTB,ListTB):
932 932 """Subclass ListTB but allow calling with a traceback.
933 933
934 934 It can thus be used as a sys.excepthook for Python > 2.1.
935 935
936 936 Also adds 'Context' and 'Verbose' modes, not available in ListTB.
937 937
938 938 Allows a tb_offset to be specified. This is useful for situations where
939 939 one needs to remove a number of topmost frames from the traceback (such as
940 940 occurs with python programs that themselves execute other python code,
941 941 like Python shells). """
942 942
943 943 def __init__(self, mode = 'Plain', color_scheme='Linux',
944 944 tb_offset = 0,long_header=0,call_pdb=0,include_vars=0):
945 945
946 946 # NEVER change the order of this list. Put new modes at the end:
947 947 self.valid_modes = ['Plain','Context','Verbose']
948 948 self.verbose_modes = self.valid_modes[1:3]
949 949
950 950 VerboseTB.__init__(self,color_scheme,tb_offset,long_header,
951 951 call_pdb=call_pdb,include_vars=include_vars)
952 952 self.set_mode(mode)
953 953
954 954 def _extract_tb(self,tb):
955 955 if tb:
956 956 return traceback.extract_tb(tb)
957 957 else:
958 958 return None
959 959
960 960 def text(self, etype, value, tb,context=5,mode=None):
961 961 """Return formatted traceback.
962 962
963 963 If the optional mode parameter is given, it overrides the current
964 964 mode."""
965 965
966 966 if mode is None:
967 967 mode = self.mode
968 968 if mode in self.verbose_modes:
969 969 # verbose modes need a full traceback
970 970 return VerboseTB.text(self,etype, value, tb,context=5)
971 971 else:
972 972 # We must check the source cache because otherwise we can print
973 973 # out-of-date source code.
974 974 linecache.checkcache()
975 975 # Now we can extract and format the exception
976 976 elist = self._extract_tb(tb)
977 977 if len(elist) > self.tb_offset:
978 978 del elist[:self.tb_offset]
979 979 return ListTB.text(self,etype,value,elist)
980 980
981 981 def set_mode(self,mode=None):
982 982 """Switch to the desired mode.
983 983
984 984 If mode is not specified, cycles through the available modes."""
985 985
986 986 if not mode:
987 987 new_idx = ( self.valid_modes.index(self.mode) + 1 ) % \
988 988 len(self.valid_modes)
989 989 self.mode = self.valid_modes[new_idx]
990 990 elif mode not in self.valid_modes:
991 991 raise ValueError, 'Unrecognized mode in FormattedTB: <'+mode+'>\n'\
992 992 'Valid modes: '+str(self.valid_modes)
993 993 else:
994 994 self.mode = mode
995 995 # include variable details only in 'Verbose' mode
996 996 self.include_vars = (self.mode == self.valid_modes[2])
997 997
998 998 # some convenient shorcuts
999 999 def plain(self):
1000 1000 self.set_mode(self.valid_modes[0])
1001 1001
1002 1002 def context(self):
1003 1003 self.set_mode(self.valid_modes[1])
1004 1004
1005 1005 def verbose(self):
1006 1006 self.set_mode(self.valid_modes[2])
1007 1007
1008 1008 #----------------------------------------------------------------------------
1009 1009 class AutoFormattedTB(FormattedTB):
1010 1010 """A traceback printer which can be called on the fly.
1011 1011
1012 1012 It will find out about exceptions by itself.
1013 1013
1014 1014 A brief example:
1015 1015
1016 1016 AutoTB = AutoFormattedTB(mode = 'Verbose',color_scheme='Linux')
1017 1017 try:
1018 1018 ...
1019 1019 except:
1020 1020 AutoTB() # or AutoTB(out=logfile) where logfile is an open file object
1021 1021 """
1022 1022
1023 1023 def __call__(self,etype=None,evalue=None,etb=None,
1024 1024 out=None,tb_offset=None):
1025 1025 """Print out a formatted exception traceback.
1026 1026
1027 1027 Optional arguments:
1028 1028 - out: an open file-like object to direct output to.
1029 1029
1030 1030 - tb_offset: the number of frames to skip over in the stack, on a
1031 1031 per-call basis (this overrides temporarily the instance's tb_offset
1032 1032 given at initialization time. """
1033 1033
1034 1034 if out is None:
1035 out = sys.stdout if self.out_stream=='stdout' else self.out_stream
1036 Term.cout.flush()
1035 if self.out_stream == 'stdout':
1036 out = sys.stdout
1037 else:
1038 out = IPython.utils.io.Term.cerr
1039 out.flush()
1037 1040 if tb_offset is not None:
1038 1041 tb_offset, self.tb_offset = self.tb_offset, tb_offset
1039 1042 out.write(self.text(etype, evalue, etb))
1040 1043 out.write('\n')
1041 1044 self.tb_offset = tb_offset
1042 1045 else:
1043 1046 out.write(self.text(etype, evalue, etb))
1044 1047 out.write('\n')
1045 1048 out.flush()
1046 1049 try:
1047 1050 self.debugger()
1048 1051 except KeyboardInterrupt:
1049 1052 print "\nKeyboardInterrupt"
1050 1053
1051 1054 def text(self,etype=None,value=None,tb=None,context=5,mode=None):
1052 1055 if etype is None:
1053 1056 etype,value,tb = sys.exc_info()
1054 1057 self.tb = tb
1055 1058 return FormattedTB.text(self,etype,value,tb,context=5,mode=mode)
1056 1059
1057 1060 #---------------------------------------------------------------------------
1058 1061 # A simple class to preserve Nathan's original functionality.
1059 1062 class ColorTB(FormattedTB):
1060 1063 """Shorthand to initialize a FormattedTB in Linux colors mode."""
1061 1064 def __init__(self,color_scheme='Linux',call_pdb=0):
1062 1065 FormattedTB.__init__(self,color_scheme=color_scheme,
1063 1066 call_pdb=call_pdb)
1064 1067
1065 1068 #----------------------------------------------------------------------------
1066 1069 # module testing (minimal)
1067 1070 if __name__ == "__main__":
1068 1071 def spam(c, (d, e)):
1069 1072 x = c + d
1070 1073 y = c * d
1071 1074 foo(x, y)
1072 1075
1073 1076 def foo(a, b, bar=1):
1074 1077 eggs(a, b + bar)
1075 1078
1076 1079 def eggs(f, g, z=globals()):
1077 1080 h = f + g
1078 1081 i = f - g
1079 1082 return h / i
1080 1083
1081 1084 print ''
1082 1085 print '*** Before ***'
1083 1086 try:
1084 1087 print spam(1, (2, 3))
1085 1088 except:
1086 1089 traceback.print_exc()
1087 1090 print ''
1088 1091
1089 1092 handler = ColorTB()
1090 1093 print '*** ColorTB ***'
1091 1094 try:
1092 1095 print spam(1, (2, 3))
1093 1096 except:
1094 1097 apply(handler, sys.exc_info() )
1095 1098 print ''
1096 1099
1097 1100 handler = VerboseTB()
1098 1101 print '*** VerboseTB ***'
1099 1102 try:
1100 1103 print spam(1, (2, 3))
1101 1104 except:
1102 1105 apply(handler, sys.exc_info() )
1103 1106 print ''
1104 1107
@@ -1,518 +1,518 b''
1 1 #!/usr/bin/python
2 2 # -*- coding: iso-8859-15 -*-
3 3 '''
4 4 Provides IPython remote instance.
5 5
6 6 @author: Laurent Dufrechou
7 7 laurent.dufrechou _at_ gmail.com
8 8 @license: BSD
9 9
10 10 All rights reserved. This program and the accompanying materials are made
11 11 available under the terms of the BSD which accompanies this distribution, and
12 12 is available at U{http://www.opensource.org/licenses/bsd-license.php}
13 13 '''
14 14
15 15 __version__ = 0.9
16 16 __author__ = "Laurent Dufrechou"
17 17 __email__ = "laurent.dufrechou _at_ gmail.com"
18 18 __license__ = "BSD"
19 19
20 20 import re
21 21 import sys
22 22 import os
23 23 import locale
24 24 from thread_ex import ThreadEx
25 25
26 26 from IPython.core import iplib
27 from IPython.utils.io import Term
27 import IPython.utils.io
28 28
29 29 ##############################################################################
30 30 class _Helper(object):
31 31 """Redefine the built-in 'help'.
32 32 This is a wrapper around pydoc.help (with a twist).
33 33 """
34 34
35 35 def __init__(self, pager):
36 36 self._pager = pager
37 37
38 38 def __repr__(self):
39 39 return "Type help() for interactive help, " \
40 40 "or help(object) for help about object."
41 41
42 42 def __call__(self, *args, **kwds):
43 43 class DummyWriter(object):
44 44 '''Dumy class to handle help output'''
45 45 def __init__(self, pager):
46 46 self._pager = pager
47 47
48 48 def write(self, data):
49 49 '''hook to fill self._pager'''
50 50 self._pager(data)
51 51
52 52 import pydoc
53 53 pydoc.help.output = DummyWriter(self._pager)
54 54 pydoc.help.interact = lambda :1
55 55
56 56 return pydoc.help(*args, **kwds)
57 57
58 58
59 59 ##############################################################################
60 60 class _CodeExecutor(ThreadEx):
61 61 ''' Thread that execute ipython code '''
62 62 def __init__(self, instance):
63 63 ThreadEx.__init__(self)
64 64 self.instance = instance
65 65
66 66 def run(self):
67 67 '''Thread main loop'''
68 68 try:
69 69 self.instance._doc_text = None
70 70 self.instance._help_text = None
71 71 self.instance._execute()
72 72 # used for uper class to generate event after execution
73 73 self.instance._after_execute()
74 74
75 75 except KeyboardInterrupt:
76 76 pass
77 77
78 78
79 79 ##############################################################################
80 80 class NonBlockingIPShell(object):
81 81 '''
82 82 Create an IPython instance, running the commands in a separate,
83 83 non-blocking thread.
84 84 This allows embedding in any GUI without blockage.
85 85
86 86 Note: The ThreadEx class supports asynchroneous function call
87 87 via raise_exc()
88 88 '''
89 89
90 90 def __init__(self, user_ns={}, user_global_ns=None,
91 91 cin=None, cout=None, cerr=None,
92 92 ask_exit_handler=None):
93 93 '''
94 94 @param user_ns: User namespace.
95 95 @type user_ns: dictionary
96 96 @param user_global_ns: User global namespace.
97 97 @type user_global_ns: dictionary.
98 98 @param cin: Console standard input.
99 99 @type cin: IO stream
100 100 @param cout: Console standard output.
101 101 @type cout: IO stream
102 102 @param cerr: Console standard error.
103 103 @type cerr: IO stream
104 104 @param exit_handler: Replacement for builtin exit() function
105 105 @type exit_handler: function
106 106 @param time_loop: Define the sleep time between two thread's loop
107 107 @type int
108 108 '''
109 109 #ipython0 initialisation
110 110 self._IP = None
111 111 self.init_ipython0(user_ns, user_global_ns,
112 112 cin, cout, cerr,
113 113 ask_exit_handler)
114 114
115 115 #vars used by _execute
116 116 self._iter_more = 0
117 117 self._history_level = 0
118 118 self._complete_sep = re.compile('[\s\{\}\[\]\(\)\=]')
119 119 self._prompt = str(self._IP.outputcache.prompt1).strip()
120 120
121 121 #thread working vars
122 122 self._line_to_execute = ''
123 123 self._threading = True
124 124
125 125 #vars that will be checked by GUI loop to handle thread states...
126 126 #will be replaced later by PostEvent GUI funtions...
127 127 self._doc_text = None
128 128 self._help_text = None
129 129 self._add_button = None
130 130
131 131 def init_ipython0(self, user_ns={}, user_global_ns=None,
132 132 cin=None, cout=None, cerr=None,
133 133 ask_exit_handler=None):
134 134 ''' Initialize an ipython0 instance '''
135 135
136 136 #first we redefine in/out/error functions of IPython
137 137 #BUG: we've got a limitation form ipython0 there
138 138 #only one instance can be instanciated else tehre will be
139 139 #cin/cout/cerr clash...
140 140 if cin:
141 141 Term.cin = cin
142 142 if cout:
143 143 Term.cout = cout
144 144 if cerr:
145 145 Term.cerr = cerr
146 146
147 147 excepthook = sys.excepthook
148 148
149 149 #Hack to save sys.displayhook, because ipython seems to overwrite it...
150 150 self.sys_displayhook_ori = sys.displayhook
151 151 ipython0 = iplib.InteractiveShell(
152 152 parent=None, config=None,
153 153 user_ns=user_ns,
154 154 user_global_ns=user_global_ns
155 155 )
156 156 self._IP = ipython0
157 157
158 158 #we save ipython0 displayhook and we restore sys.displayhook
159 159 self.displayhook = sys.displayhook
160 160 sys.displayhook = self.sys_displayhook_ori
161 161
162 162 #we replace IPython default encoding by wx locale encoding
163 163 loc = locale.getpreferredencoding()
164 164 if loc:
165 165 self._IP.stdin_encoding = loc
166 166 #we replace the ipython default pager by our pager
167 167 self._IP.set_hook('show_in_pager', self._pager)
168 168
169 169 #we replace the ipython default shell command caller
170 170 #by our shell handler
171 171 self._IP.set_hook('shell_hook', self._shell)
172 172
173 173 #we replace the ipython default input command caller by our method
174 174 iplib.raw_input_original = self._raw_input_original
175 175 #we replace the ipython default exit command by our method
176 176 self._IP.exit = ask_exit_handler
177 177 #we replace the help command
178 178 self._IP.user_ns['help'] = _Helper(self._pager_help)
179 179
180 180 #we disable cpaste magic... until we found a way to use it properly.
181 181 def bypass_magic(self, arg):
182 182 print '%this magic is currently disabled.'
183 183 ipython0.define_magic('cpaste', bypass_magic)
184 184
185 185 import __builtin__
186 186 __builtin__.raw_input = self._raw_input
187 187
188 188 sys.excepthook = excepthook
189 189
190 190 #----------------------- Thread management section ----------------------
191 191 def do_execute(self, line):
192 192 """
193 193 Tell the thread to process the 'line' command
194 194 """
195 195
196 196 self._line_to_execute = line
197 197
198 198 if self._threading:
199 199 #we launch the ipython line execution in a thread to make it
200 200 #interruptible with include it in self namespace to be able
201 201 #to call ce.raise_exc(KeyboardInterrupt)
202 202 self.ce = _CodeExecutor(self)
203 203 self.ce.start()
204 204 else:
205 205 try:
206 206 self._doc_text = None
207 207 self._help_text = None
208 208 self._execute()
209 209 # used for uper class to generate event after execution
210 210 self._after_execute()
211 211
212 212 except KeyboardInterrupt:
213 213 pass
214 214
215 215 #----------------------- IPython management section ----------------------
216 216 def get_threading(self):
217 217 """
218 218 Returns threading status, is set to True, then each command sent to
219 219 the interpreter will be executed in a separated thread allowing,
220 220 for example, breaking a long running commands.
221 221 Disallowing it, permits better compatibilty with instance that is embedding
222 222 IPython instance.
223 223
224 224 @return: Execution method
225 225 @rtype: bool
226 226 """
227 227 return self._threading
228 228
229 229 def set_threading(self, state):
230 230 """
231 231 Sets threading state, if set to True, then each command sent to
232 232 the interpreter will be executed in a separated thread allowing,
233 233 for example, breaking a long running commands.
234 234 Disallowing it, permits better compatibilty with instance that is embedding
235 235 IPython instance.
236 236
237 237 @param state: Sets threading state
238 238 @type bool
239 239 """
240 240 self._threading = state
241 241
242 242 def get_doc_text(self):
243 243 """
244 244 Returns the output of the processing that need to be paged (if any)
245 245
246 246 @return: The std output string.
247 247 @rtype: string
248 248 """
249 249 return self._doc_text
250 250
251 251 def get_help_text(self):
252 252 """
253 253 Returns the output of the processing that need to be paged via help pager(if any)
254 254
255 255 @return: The std output string.
256 256 @rtype: string
257 257 """
258 258 return self._help_text
259 259
260 260 def get_banner(self):
261 261 """
262 262 Returns the IPython banner for useful info on IPython instance
263 263
264 264 @return: The banner string.
265 265 @rtype: string
266 266 """
267 267 return self._IP.banner
268 268
269 269 def get_prompt_count(self):
270 270 """
271 271 Returns the prompt number.
272 272 Each time a user execute a line in the IPython shell the prompt count is increased
273 273
274 274 @return: The prompt number
275 275 @rtype: int
276 276 """
277 277 return self._IP.outputcache.prompt_count
278 278
279 279 def get_prompt(self):
280 280 """
281 281 Returns current prompt inside IPython instance
282 282 (Can be In [...]: ot ...:)
283 283
284 284 @return: The current prompt.
285 285 @rtype: string
286 286 """
287 287 return self._prompt
288 288
289 289 def get_indentation(self):
290 290 """
291 291 Returns the current indentation level
292 292 Usefull to put the caret at the good start position if we want to do autoindentation.
293 293
294 294 @return: The indentation level.
295 295 @rtype: int
296 296 """
297 297 return self._IP.indent_current_nsp
298 298
299 299 def update_namespace(self, ns_dict):
300 300 '''
301 301 Add the current dictionary to the shell namespace.
302 302
303 303 @param ns_dict: A dictionary of symbol-values.
304 304 @type ns_dict: dictionary
305 305 '''
306 306 self._IP.user_ns.update(ns_dict)
307 307
308 308 def complete(self, line):
309 309 '''
310 310 Returns an auto completed line and/or posibilities for completion.
311 311
312 312 @param line: Given line so far.
313 313 @type line: string
314 314
315 315 @return: Line completed as for as possible,
316 316 and possible further completions.
317 317 @rtype: tuple
318 318 '''
319 319 split_line = self._complete_sep.split(line)
320 320 possibilities = self._IP.complete(split_line[-1])
321 321 if possibilities:
322 322
323 323 def _common_prefix(str1, str2):
324 324 '''
325 325 Reduction function. returns common prefix of two given strings.
326 326
327 327 @param str1: First string.
328 328 @type str1: string
329 329 @param str2: Second string
330 330 @type str2: string
331 331
332 332 @return: Common prefix to both strings.
333 333 @rtype: string
334 334 '''
335 335 for i in range(len(str1)):
336 336 if not str2.startswith(str1[:i+1]):
337 337 return str1[:i]
338 338 return str1
339 339 common_prefix = reduce(_common_prefix, possibilities)
340 340 completed = line[:-len(split_line[-1])]+common_prefix
341 341 else:
342 342 completed = line
343 343 return completed, possibilities
344 344
345 345 def history_back(self):
346 346 '''
347 347 Provides one history command back.
348 348
349 349 @return: The command string.
350 350 @rtype: string
351 351 '''
352 352 history = ''
353 353 #the below while loop is used to suppress empty history lines
354 354 while((history == '' or history == '\n') and self._history_level >0):
355 355 if self._history_level >= 1:
356 356 self._history_level -= 1
357 357 history = self._get_history()
358 358 return history
359 359
360 360 def history_forward(self):
361 361 '''
362 362 Provides one history command forward.
363 363
364 364 @return: The command string.
365 365 @rtype: string
366 366 '''
367 367 history = ''
368 368 #the below while loop is used to suppress empty history lines
369 369 while((history == '' or history == '\n') \
370 370 and self._history_level <= self._get_history_max_index()):
371 371 if self._history_level < self._get_history_max_index():
372 372 self._history_level += 1
373 373 history = self._get_history()
374 374 else:
375 375 if self._history_level == self._get_history_max_index():
376 376 history = self._get_history()
377 377 self._history_level += 1
378 378 else:
379 379 history = ''
380 380 return history
381 381
382 382 def init_history_index(self):
383 383 '''
384 384 set history to last command entered
385 385 '''
386 386 self._history_level = self._get_history_max_index()+1
387 387
388 388 #----------------------- IPython PRIVATE management section --------------
389 389 def _after_execute(self):
390 390 '''
391 391 Can be redefined to generate post event after excution is done
392 392 '''
393 393 pass
394 394
395 395 def _ask_exit(self):
396 396 '''
397 397 Can be redefined to generate post event to exit the Ipython shell
398 398 '''
399 399 pass
400 400
401 401 def _get_history_max_index(self):
402 402 '''
403 403 returns the max length of the history buffer
404 404
405 405 @return: history length
406 406 @rtype: int
407 407 '''
408 408 return len(self._IP.input_hist_raw)-1
409 409
410 410 def _get_history(self):
411 411 '''
412 412 Get's the command string of the current history level.
413 413
414 414 @return: Historic command stri
415 415 @rtype: string
416 416 '''
417 417 rv = self._IP.input_hist_raw[self._history_level].strip('\n')
418 418 return rv
419 419
420 420 def _pager_help(self, text):
421 421 '''
422 422 This function is used as a callback replacment to IPython help pager function
423 423
424 424 It puts the 'text' value inside the self._help_text string that can be retrived via
425 425 get_help_text function.
426 426 '''
427 427 if self._help_text == None:
428 428 self._help_text = text
429 429 else:
430 430 self._help_text += text
431 431
432 432 def _pager(self, IP, text):
433 433 '''
434 434 This function is used as a callback replacment to IPython pager function
435 435
436 436 It puts the 'text' value inside the self._doc_text string that can be retrived via
437 437 get_doc_text function.
438 438 '''
439 439 self._doc_text = text
440 440
441 441 def _raw_input_original(self, prompt=''):
442 442 '''
443 443 Custom raw_input() replacement. Get's current line from console buffer.
444 444
445 445 @param prompt: Prompt to print. Here for compatability as replacement.
446 446 @type prompt: string
447 447
448 448 @return: The current command line text.
449 449 @rtype: string
450 450 '''
451 451 return self._line_to_execute
452 452
453 453 def _raw_input(self, prompt=''):
454 454 """ A replacement from python's raw_input.
455 455 """
456 456 raise NotImplementedError
457 457
458 458 def _execute(self):
459 459 '''
460 460 Executes the current line provided by the shell object.
461 461 '''
462 462
463 463 orig_stdout = sys.stdout
464 464 sys.stdout = Term.cout
465 465 #self.sys_displayhook_ori = sys.displayhook
466 466 #sys.displayhook = self.displayhook
467 467
468 468 try:
469 469 line = self._IP.raw_input(None, self._iter_more)
470 470 if self._IP.autoindent:
471 471 self._IP.readline_startup_hook(None)
472 472
473 473 except KeyboardInterrupt:
474 474 self._IP.write('\nKeyboardInterrupt\n')
475 475 self._IP.resetbuffer()
476 476 # keep cache in sync with the prompt counter:
477 477 self._IP.outputcache.prompt_count -= 1
478 478
479 479 if self._IP.autoindent:
480 480 self._IP.indent_current_nsp = 0
481 481 self._iter_more = 0
482 482 except:
483 483 self._IP.showtraceback()
484 484 else:
485 485 self._IP.write(str(self._IP.outputcache.prompt_out).strip())
486 486 self._iter_more = self._IP.push_line(line)
487 487 if (self._IP.SyntaxTB.last_syntax_error and \
488 488 self._IP.autoedit_syntax):
489 489 self._IP.edit_syntax_error()
490 490 if self._iter_more:
491 491 self._prompt = str(self._IP.outputcache.prompt2).strip()
492 492 if self._IP.autoindent:
493 493 self._IP.readline_startup_hook(self._IP.pre_readline)
494 494 else:
495 495 self._prompt = str(self._IP.outputcache.prompt1).strip()
496 496 self._IP.indent_current_nsp = 0 #we set indentation to 0
497 497
498 498 sys.stdout = orig_stdout
499 499 #sys.displayhook = self.sys_displayhook_ori
500 500
501 501 def _shell(self, ip, cmd):
502 502 '''
503 503 Replacement method to allow shell commands without them blocking.
504 504
505 505 @param ip: Ipython instance, same as self._IP
506 506 @type cmd: Ipython instance
507 507 @param cmd: Shell command to execute.
508 508 @type cmd: string
509 509 '''
510 510 stdin, stdout = os.popen4(cmd)
511 511 result = stdout.read().decode('cp437').\
512 512 encode(locale.getpreferredencoding())
513 513 #we use print command because the shell command is called
514 514 #inside IPython instance and thus is redirected to thread cout
515 515 #"\x01\x1b[1;36m\x02" <-- add colour to the text...
516 516 print "\x01\x1b[1;36m\x02"+result
517 517 stdout.close()
518 518 stdin.close()
@@ -1,2328 +1,2328 b''
1 1 # -*- coding: iso-8859-1 -*-
2 2
3 3 """
4 4 ``ipipe`` provides classes to be used in an interactive Python session. Doing a
5 5 ``from ipipe import *`` is the preferred way to do this. The name of all
6 6 objects imported this way starts with ``i`` to minimize collisions.
7 7
8 8 ``ipipe`` supports "pipeline expressions", which is something resembling Unix
9 9 pipes. An example is::
10 10
11 11 >>> ienv | isort("key.lower()")
12 12
13 13 This gives a listing of all environment variables sorted by name.
14 14
15 15
16 16 There are three types of objects in a pipeline expression:
17 17
18 18 * ``Table``s: These objects produce items. Examples are ``ils`` (listing the
19 19 current directory, ``ienv`` (listing environment variables), ``ipwd`` (listing
20 20 user accounts) and ``igrp`` (listing user groups). A ``Table`` must be the
21 21 first object in a pipe expression.
22 22
23 23 * ``Pipe``s: These objects sit in the middle of a pipe expression. They
24 24 transform the input in some way (e.g. filtering or sorting it). Examples are:
25 25 ``ifilter`` (which filters the input pipe), ``isort`` (which sorts the input
26 26 pipe) and ``ieval`` (which evaluates a function or expression for each object
27 27 in the input pipe).
28 28
29 29 * ``Display``s: These objects can be put as the last object in a pipeline
30 30 expression. There are responsible for displaying the result of the pipeline
31 31 expression. If a pipeline expression doesn't end in a display object a default
32 32 display objects will be used. One example is ``ibrowse`` which is a ``curses``
33 33 based browser.
34 34
35 35
36 36 Adding support for pipeline expressions to your own objects can be done through
37 37 three extensions points (all of them optional):
38 38
39 39 * An object that will be displayed as a row by a ``Display`` object should
40 40 implement the method ``__xattrs__(self, mode)`` method or register an
41 41 implementation of the generic function ``xattrs``. For more info see ``xattrs``.
42 42
43 43 * When an object ``foo`` is displayed by a ``Display`` object, the generic
44 44 function ``xrepr`` is used.
45 45
46 46 * Objects that can be iterated by ``Pipe``s must iterable. For special cases,
47 47 where iteration for display is different than the normal iteration a special
48 48 implementation can be registered with the generic function ``xiter``. This
49 49 makes it possible to use dictionaries and modules in pipeline expressions,
50 50 for example::
51 51
52 52 >>> import sys
53 53 >>> sys | ifilter("isinstance(value, int)") | idump
54 54 key |value
55 55 api_version| 1012
56 56 dllhandle | 503316480
57 57 hexversion | 33817328
58 58 maxint |2147483647
59 59 maxunicode | 65535
60 60 >>> sys.modules | ifilter("_.value is not None") | isort("_.key.lower()")
61 61 ...
62 62
63 63 Note: The expression strings passed to ``ifilter()`` and ``isort()`` can
64 64 refer to the object to be filtered or sorted via the variable ``_`` and to any
65 65 of the attributes of the object, i.e.::
66 66
67 67 >>> sys.modules | ifilter("_.value is not None") | isort("_.key.lower()")
68 68
69 69 does the same as::
70 70
71 71 >>> sys.modules | ifilter("value is not None") | isort("key.lower()")
72 72
73 73 In addition to expression strings, it's possible to pass callables (taking
74 74 the object as an argument) to ``ifilter()``, ``isort()`` and ``ieval()``::
75 75
76 76 >>> sys | ifilter(lambda _:isinstance(_.value, int)) \
77 77 ... | ieval(lambda _: (_.key, hex(_.value))) | idump
78 78 0 |1
79 79 api_version|0x3f4
80 80 dllhandle |0x1e000000
81 81 hexversion |0x20402f0
82 82 maxint |0x7fffffff
83 83 maxunicode |0xffff
84 84 """
85 85
86 86 skip_doctest = True # ignore top-level docstring as a doctest.
87 87
88 88 import sys, os, os.path, stat, glob, new, csv, datetime, types
89 89 import itertools, mimetypes, StringIO
90 90
91 91 try: # Python 2.3 compatibility
92 92 import collections
93 93 except ImportError:
94 94 deque = list
95 95 else:
96 96 deque = collections.deque
97 97
98 98 try: # Python 2.3 compatibility
99 99 set
100 100 except NameError:
101 101 import sets
102 102 set = sets.Set
103 103
104 104 try: # Python 2.3 compatibility
105 105 sorted
106 106 except NameError:
107 107 def sorted(iterator, key=None, reverse=False):
108 108 items = list(iterator)
109 109 if key is not None:
110 110 items.sort(lambda i1, i2: cmp(key(i1), key(i2)))
111 111 else:
112 112 items.sort()
113 113 if reverse:
114 114 items.reverse()
115 115 return items
116 116
117 117 try: # Python 2.4 compatibility
118 118 GeneratorExit
119 119 except NameError:
120 120 GeneratorExit = SystemExit
121 121
122 122 try:
123 123 import pwd
124 124 except ImportError:
125 125 pwd = None
126 126
127 127 try:
128 128 import grp
129 129 except ImportError:
130 130 grp = None
131 131
132 132 from IPython.external import simplegeneric
133 133 from IPython.external import path
134 134
135 135 try:
136 from IPython.utils.io import Term
136 import IPython.utils.io
137 137 from IPython.utils import generics
138 138 except ImportError:
139 139 Term = None
140 140 generics = None
141 141
142 142 from IPython.core import ipapi
143 143
144 144
145 145 __all__ = [
146 146 "ifile", "ils", "iglob", "iwalk", "ipwdentry", "ipwd", "igrpentry", "igrp",
147 147 "icsv", "ix", "ichain", "isort", "ifilter", "ieval", "ienum",
148 148 "ienv", "ihist", "ialias", "icap", "idump", "iless"
149 149 ]
150 150
151 151
152 152 os.stat_float_times(True) # enable microseconds
153 153
154 154
155 155 class AttrNamespace(object):
156 156 """
157 157 Helper class that is used for providing a namespace for evaluating
158 158 expressions containing attribute names of an object.
159 159 """
160 160 def __init__(self, wrapped):
161 161 self.wrapped = wrapped
162 162
163 163 def __getitem__(self, name):
164 164 if name == "_":
165 165 return self.wrapped
166 166 try:
167 167 return getattr(self.wrapped, name)
168 168 except AttributeError:
169 169 raise KeyError(name)
170 170
171 171 # Python 2.3 compatibility
172 172 # use eval workaround to find out which names are used in the
173 173 # eval string and put them into the locals. This works for most
174 174 # normal uses case, bizarre ones like accessing the locals()
175 175 # will fail
176 176 try:
177 177 eval("_", None, AttrNamespace(None))
178 178 except TypeError:
179 179 real_eval = eval
180 180 def eval(codestring, _globals, _locals):
181 181 """
182 182 eval(source[, globals[, locals]]) -> value
183 183
184 184 Evaluate the source in the context of globals and locals.
185 185 The source may be a string representing a Python expression
186 186 or a code object as returned by compile().
187 187 The globals must be a dictionary and locals can be any mappping.
188 188
189 189 This function is a workaround for the shortcomings of
190 190 Python 2.3's eval.
191 191 """
192 192
193 193 if isinstance(codestring, basestring):
194 194 code = compile(codestring, "_eval", "eval")
195 195 else:
196 196 code = codestring
197 197 newlocals = {}
198 198 for name in code.co_names:
199 199 try:
200 200 newlocals[name] = _locals[name]
201 201 except KeyError:
202 202 pass
203 203 return real_eval(code, _globals, newlocals)
204 204
205 205
206 206 noitem = object()
207 207
208 208
209 209 def item(iterator, index, default=noitem):
210 210 """
211 211 Return the ``index``th item from the iterator ``iterator``.
212 212 ``index`` must be an integer (negative integers are relative to the
213 213 end (i.e. the last items produced by the iterator)).
214 214
215 215 If ``default`` is given, this will be the default value when
216 216 the iterator doesn't contain an item at this position. Otherwise an
217 217 ``IndexError`` will be raised.
218 218
219 219 Note that using this function will partially or totally exhaust the
220 220 iterator.
221 221 """
222 222 i = index
223 223 if i>=0:
224 224 for item in iterator:
225 225 if not i:
226 226 return item
227 227 i -= 1
228 228 else:
229 229 i = -index
230 230 cache = deque()
231 231 for item in iterator:
232 232 cache.append(item)
233 233 if len(cache)>i:
234 234 cache.popleft()
235 235 if len(cache)==i:
236 236 return cache.popleft()
237 237 if default is noitem:
238 238 raise IndexError(index)
239 239 else:
240 240 return default
241 241
242 242
243 243 def getglobals(g):
244 244 """
245 245 Return the global namespace that is used for expression strings in
246 246 ``ifilter`` and others. This is ``g`` or (if ``g`` is ``None``) IPython's
247 247 user namespace.
248 248 """
249 249 if g is None:
250 250 if ipapi is not None:
251 251 api = ipapi.get()
252 252 if api is not None:
253 253 return api.user_ns
254 254 return globals()
255 255 return g
256 256
257 257
258 258 class Descriptor(object):
259 259 """
260 260 A ``Descriptor`` object is used for describing the attributes of objects.
261 261 """
262 262 def __hash__(self):
263 263 return hash(self.__class__) ^ hash(self.key())
264 264
265 265 def __eq__(self, other):
266 266 return self.__class__ is other.__class__ and self.key() == other.key()
267 267
268 268 def __ne__(self, other):
269 269 return self.__class__ is not other.__class__ or self.key() != other.key()
270 270
271 271 def key(self):
272 272 pass
273 273
274 274 def name(self):
275 275 """
276 276 Return the name of this attribute for display by a ``Display`` object
277 277 (e.g. as a column title).
278 278 """
279 279 key = self.key()
280 280 if key is None:
281 281 return "_"
282 282 return str(key)
283 283
284 284 def attrtype(self, obj):
285 285 """
286 286 Return the type of this attribute (i.e. something like "attribute" or
287 287 "method").
288 288 """
289 289
290 290 def valuetype(self, obj):
291 291 """
292 292 Return the type of this attribute value of the object ``obj``.
293 293 """
294 294
295 295 def value(self, obj):
296 296 """
297 297 Return the value of this attribute of the object ``obj``.
298 298 """
299 299
300 300 def doc(self, obj):
301 301 """
302 302 Return the documentation for this attribute.
303 303 """
304 304
305 305 def shortdoc(self, obj):
306 306 """
307 307 Return a short documentation for this attribute (defaulting to the
308 308 first line).
309 309 """
310 310 doc = self.doc(obj)
311 311 if doc is not None:
312 312 doc = doc.strip().splitlines()[0].strip()
313 313 return doc
314 314
315 315 def iter(self, obj):
316 316 """
317 317 Return an iterator for this attribute of the object ``obj``.
318 318 """
319 319 return xiter(self.value(obj))
320 320
321 321
322 322 class SelfDescriptor(Descriptor):
323 323 """
324 324 A ``SelfDescriptor`` describes the object itself.
325 325 """
326 326 def key(self):
327 327 return None
328 328
329 329 def attrtype(self, obj):
330 330 return "self"
331 331
332 332 def valuetype(self, obj):
333 333 return type(obj)
334 334
335 335 def value(self, obj):
336 336 return obj
337 337
338 338 def __repr__(self):
339 339 return "Self"
340 340
341 341 selfdescriptor = SelfDescriptor() # there's no need for more than one
342 342
343 343
344 344 class AttributeDescriptor(Descriptor):
345 345 """
346 346 An ``AttributeDescriptor`` describes a simple attribute of an object.
347 347 """
348 348 __slots__ = ("_name", "_doc")
349 349
350 350 def __init__(self, name, doc=None):
351 351 self._name = name
352 352 self._doc = doc
353 353
354 354 def key(self):
355 355 return self._name
356 356
357 357 def doc(self, obj):
358 358 return self._doc
359 359
360 360 def attrtype(self, obj):
361 361 return "attr"
362 362
363 363 def valuetype(self, obj):
364 364 return type(getattr(obj, self._name))
365 365
366 366 def value(self, obj):
367 367 return getattr(obj, self._name)
368 368
369 369 def __repr__(self):
370 370 if self._doc is None:
371 371 return "Attribute(%r)" % self._name
372 372 else:
373 373 return "Attribute(%r, %r)" % (self._name, self._doc)
374 374
375 375
376 376 class IndexDescriptor(Descriptor):
377 377 """
378 378 An ``IndexDescriptor`` describes an "attribute" of an object that is fetched
379 379 via ``__getitem__``.
380 380 """
381 381 __slots__ = ("_index",)
382 382
383 383 def __init__(self, index):
384 384 self._index = index
385 385
386 386 def key(self):
387 387 return self._index
388 388
389 389 def attrtype(self, obj):
390 390 return "item"
391 391
392 392 def valuetype(self, obj):
393 393 return type(obj[self._index])
394 394
395 395 def value(self, obj):
396 396 return obj[self._index]
397 397
398 398 def __repr__(self):
399 399 return "Index(%r)" % self._index
400 400
401 401
402 402 class MethodDescriptor(Descriptor):
403 403 """
404 404 A ``MethodDescriptor`` describes a method of an object that can be called
405 405 without argument. Note that this method shouldn't change the object.
406 406 """
407 407 __slots__ = ("_name", "_doc")
408 408
409 409 def __init__(self, name, doc=None):
410 410 self._name = name
411 411 self._doc = doc
412 412
413 413 def key(self):
414 414 return self._name
415 415
416 416 def doc(self, obj):
417 417 if self._doc is None:
418 418 return getattr(obj, self._name).__doc__
419 419 return self._doc
420 420
421 421 def attrtype(self, obj):
422 422 return "method"
423 423
424 424 def valuetype(self, obj):
425 425 return type(self.value(obj))
426 426
427 427 def value(self, obj):
428 428 return getattr(obj, self._name)()
429 429
430 430 def __repr__(self):
431 431 if self._doc is None:
432 432 return "Method(%r)" % self._name
433 433 else:
434 434 return "Method(%r, %r)" % (self._name, self._doc)
435 435
436 436
437 437 class IterAttributeDescriptor(Descriptor):
438 438 """
439 439 An ``IterAttributeDescriptor`` works like an ``AttributeDescriptor`` but
440 440 doesn't return an attribute values (because this value might be e.g. a large
441 441 list).
442 442 """
443 443 __slots__ = ("_name", "_doc")
444 444
445 445 def __init__(self, name, doc=None):
446 446 self._name = name
447 447 self._doc = doc
448 448
449 449 def key(self):
450 450 return self._name
451 451
452 452 def doc(self, obj):
453 453 return self._doc
454 454
455 455 def attrtype(self, obj):
456 456 return "iter"
457 457
458 458 def valuetype(self, obj):
459 459 return noitem
460 460
461 461 def value(self, obj):
462 462 return noitem
463 463
464 464 def iter(self, obj):
465 465 return xiter(getattr(obj, self._name))
466 466
467 467 def __repr__(self):
468 468 if self._doc is None:
469 469 return "IterAttribute(%r)" % self._name
470 470 else:
471 471 return "IterAttribute(%r, %r)" % (self._name, self._doc)
472 472
473 473
474 474 class IterMethodDescriptor(Descriptor):
475 475 """
476 476 An ``IterMethodDescriptor`` works like an ``MethodDescriptor`` but doesn't
477 477 return an attribute values (because this value might be e.g. a large list).
478 478 """
479 479 __slots__ = ("_name", "_doc")
480 480
481 481 def __init__(self, name, doc=None):
482 482 self._name = name
483 483 self._doc = doc
484 484
485 485 def key(self):
486 486 return self._name
487 487
488 488 def doc(self, obj):
489 489 if self._doc is None:
490 490 return getattr(obj, self._name).__doc__
491 491 return self._doc
492 492
493 493 def attrtype(self, obj):
494 494 return "itermethod"
495 495
496 496 def valuetype(self, obj):
497 497 return noitem
498 498
499 499 def value(self, obj):
500 500 return noitem
501 501
502 502 def iter(self, obj):
503 503 return xiter(getattr(obj, self._name)())
504 504
505 505 def __repr__(self):
506 506 if self._doc is None:
507 507 return "IterMethod(%r)" % self._name
508 508 else:
509 509 return "IterMethod(%r, %r)" % (self._name, self._doc)
510 510
511 511
512 512 class FunctionDescriptor(Descriptor):
513 513 """
514 514 A ``FunctionDescriptor`` turns a function into a descriptor. The function
515 515 will be called with the object to get the type and value of the attribute.
516 516 """
517 517 __slots__ = ("_function", "_name", "_doc")
518 518
519 519 def __init__(self, function, name=None, doc=None):
520 520 self._function = function
521 521 self._name = name
522 522 self._doc = doc
523 523
524 524 def key(self):
525 525 return self._function
526 526
527 527 def name(self):
528 528 if self._name is not None:
529 529 return self._name
530 530 return getattr(self._function, "__xname__", self._function.__name__)
531 531
532 532 def doc(self, obj):
533 533 if self._doc is None:
534 534 return self._function.__doc__
535 535 return self._doc
536 536
537 537 def attrtype(self, obj):
538 538 return "function"
539 539
540 540 def valuetype(self, obj):
541 541 return type(self._function(obj))
542 542
543 543 def value(self, obj):
544 544 return self._function(obj)
545 545
546 546 def __repr__(self):
547 547 if self._doc is None:
548 548 return "Function(%r)" % self._name
549 549 else:
550 550 return "Function(%r, %r)" % (self._name, self._doc)
551 551
552 552
553 553 class Table(object):
554 554 """
555 555 A ``Table`` is an object that produces items (just like a normal Python
556 556 iterator/generator does) and can be used as the first object in a pipeline
557 557 expression. The displayhook will open the default browser for such an object
558 558 (instead of simply printing the ``repr()`` result).
559 559 """
560 560
561 561 # We want to support ``foo`` and ``foo()`` in pipeline expression:
562 562 # So we implement the required operators (``|`` and ``+``) in the metaclass,
563 563 # instantiate the class and forward the operator to the instance
564 564 class __metaclass__(type):
565 565 def __iter__(self):
566 566 return iter(self())
567 567
568 568 def __or__(self, other):
569 569 return self() | other
570 570
571 571 def __add__(self, other):
572 572 return self() + other
573 573
574 574 def __radd__(self, other):
575 575 return other + self()
576 576
577 577 def __getitem__(self, index):
578 578 return self()[index]
579 579
580 580 def __getitem__(self, index):
581 581 return item(self, index)
582 582
583 583 def __contains__(self, item):
584 584 for haveitem in self:
585 585 if item == haveitem:
586 586 return True
587 587 return False
588 588
589 589 def __or__(self, other):
590 590 # autoinstantiate right hand side
591 591 if isinstance(other, type) and issubclass(other, (Table, Display)):
592 592 other = other()
593 593 # treat simple strings and functions as ``ieval`` instances
594 594 elif not isinstance(other, Display) and not isinstance(other, Table):
595 595 other = ieval(other)
596 596 # forward operations to the right hand side
597 597 return other.__ror__(self)
598 598
599 599 def __add__(self, other):
600 600 # autoinstantiate right hand side
601 601 if isinstance(other, type) and issubclass(other, Table):
602 602 other = other()
603 603 return ichain(self, other)
604 604
605 605 def __radd__(self, other):
606 606 # autoinstantiate left hand side
607 607 if isinstance(other, type) and issubclass(other, Table):
608 608 other = other()
609 609 return ichain(other, self)
610 610
611 611
612 612 class Pipe(Table):
613 613 """
614 614 A ``Pipe`` is an object that can be used in a pipeline expression. It
615 615 processes the objects it gets from its input ``Table``/``Pipe``. Note that
616 616 a ``Pipe`` object can't be used as the first object in a pipeline
617 617 expression, as it doesn't produces items itself.
618 618 """
619 619 class __metaclass__(Table.__metaclass__):
620 620 def __ror__(self, input):
621 621 return input | self()
622 622
623 623 def __ror__(self, input):
624 624 # autoinstantiate left hand side
625 625 if isinstance(input, type) and issubclass(input, Table):
626 626 input = input()
627 627 self.input = input
628 628 return self
629 629
630 630
631 631 def xrepr(item, mode="default"):
632 632 """
633 633 Generic function that adds color output and different display modes to ``repr``.
634 634
635 635 The result of an ``xrepr`` call is iterable and consists of ``(style, string)``
636 636 tuples. The ``style`` in this tuple must be a ``Style`` object from the
637 637 ``astring`` module. To reconfigure the output the first yielded tuple can be
638 638 a ``(aligment, full)`` tuple instead of a ``(style, string)`` tuple.
639 639 ``alignment`` can be -1 for left aligned, 0 for centered and 1 for right
640 640 aligned (the default is left alignment). ``full`` is a boolean that specifies
641 641 whether the complete output must be displayed or the ``Display`` object is
642 642 allowed to stop output after enough text has been produced (e.g. a syntax
643 643 highlighted text line would use ``True``, but for a large data structure
644 644 (i.e. a nested list, tuple or dictionary) ``False`` would be used).
645 645 The default is full output.
646 646
647 647 There are four different possible values for ``mode`` depending on where
648 648 the ``Display`` object will display ``item``:
649 649
650 650 ``"header"``
651 651 ``item`` will be displayed in a header line (this is used by ``ibrowse``).
652 652
653 653 ``"footer"``
654 654 ``item`` will be displayed in a footer line (this is used by ``ibrowse``).
655 655
656 656 ``"cell"``
657 657 ``item`` will be displayed in a table cell/list.
658 658
659 659 ``"default"``
660 660 default mode. If an ``xrepr`` implementation recursively outputs objects,
661 661 ``"default"`` must be passed in the recursive calls to ``xrepr``.
662 662
663 663 If no implementation is registered for ``item``, ``xrepr`` will try the
664 664 ``__xrepr__`` method on ``item``. If ``item`` doesn't have an ``__xrepr__``
665 665 method it falls back to ``repr``/``__repr__`` for all modes.
666 666 """
667 667 try:
668 668 func = item.__xrepr__
669 669 except AttributeError:
670 670 yield (astyle.style_default, repr(item))
671 671 else:
672 672 try:
673 673 for x in func(mode):
674 674 yield x
675 675 except (KeyboardInterrupt, SystemExit, GeneratorExit):
676 676 raise
677 677 except Exception:
678 678 yield (astyle.style_default, repr(item))
679 679 xrepr = simplegeneric.generic(xrepr)
680 680
681 681
682 682 def xrepr_none(self, mode="default"):
683 683 yield (astyle.style_type_none, repr(self))
684 684 xrepr.when_object(None)(xrepr_none)
685 685
686 686
687 687 def xrepr_noitem(self, mode="default"):
688 688 yield (2, True)
689 689 yield (astyle.style_nodata, "<?>")
690 690 xrepr.when_object(noitem)(xrepr_noitem)
691 691
692 692
693 693 def xrepr_bool(self, mode="default"):
694 694 yield (astyle.style_type_bool, repr(self))
695 695 xrepr.when_type(bool)(xrepr_bool)
696 696
697 697
698 698 def xrepr_str(self, mode="default"):
699 699 if mode == "cell":
700 700 yield (astyle.style_default, repr(self.expandtabs(tab))[1:-1])
701 701 else:
702 702 yield (astyle.style_default, repr(self))
703 703 xrepr.when_type(str)(xrepr_str)
704 704
705 705
706 706 def xrepr_unicode(self, mode="default"):
707 707 if mode == "cell":
708 708 yield (astyle.style_default, repr(self.expandtabs(tab))[2:-1])
709 709 else:
710 710 yield (astyle.style_default, repr(self))
711 711 xrepr.when_type(unicode)(xrepr_unicode)
712 712
713 713
714 714 def xrepr_number(self, mode="default"):
715 715 yield (1, True)
716 716 yield (astyle.style_type_number, repr(self))
717 717 xrepr.when_type(int)(xrepr_number)
718 718 xrepr.when_type(long)(xrepr_number)
719 719 xrepr.when_type(float)(xrepr_number)
720 720
721 721
722 722 def xrepr_complex(self, mode="default"):
723 723 yield (astyle.style_type_number, repr(self))
724 724 xrepr.when_type(complex)(xrepr_number)
725 725
726 726
727 727 def xrepr_datetime(self, mode="default"):
728 728 if mode == "cell":
729 729 # Don't use strftime() here, as this requires year >= 1900
730 730 yield (astyle.style_type_datetime,
731 731 "%04d-%02d-%02d %02d:%02d:%02d.%06d" % \
732 732 (self.year, self.month, self.day,
733 733 self.hour, self.minute, self.second,
734 734 self.microsecond),
735 735 )
736 736 else:
737 737 yield (astyle.style_type_datetime, repr(self))
738 738 xrepr.when_type(datetime.datetime)(xrepr_datetime)
739 739
740 740
741 741 def xrepr_date(self, mode="default"):
742 742 if mode == "cell":
743 743 yield (astyle.style_type_datetime,
744 744 "%04d-%02d-%02d" % (self.year, self.month, self.day))
745 745 else:
746 746 yield (astyle.style_type_datetime, repr(self))
747 747 xrepr.when_type(datetime.date)(xrepr_date)
748 748
749 749
750 750 def xrepr_time(self, mode="default"):
751 751 if mode == "cell":
752 752 yield (astyle.style_type_datetime,
753 753 "%02d:%02d:%02d.%06d" % \
754 754 (self.hour, self.minute, self.second, self.microsecond))
755 755 else:
756 756 yield (astyle.style_type_datetime, repr(self))
757 757 xrepr.when_type(datetime.time)(xrepr_time)
758 758
759 759
760 760 def xrepr_timedelta(self, mode="default"):
761 761 yield (astyle.style_type_datetime, repr(self))
762 762 xrepr.when_type(datetime.timedelta)(xrepr_timedelta)
763 763
764 764
765 765 def xrepr_type(self, mode="default"):
766 766 if self.__module__ == "__builtin__":
767 767 yield (astyle.style_type_type, self.__name__)
768 768 else:
769 769 yield (astyle.style_type_type, "%s.%s" % (self.__module__, self.__name__))
770 770 xrepr.when_type(type)(xrepr_type)
771 771
772 772
773 773 def xrepr_exception(self, mode="default"):
774 774 if self.__class__.__module__ == "exceptions":
775 775 classname = self.__class__.__name__
776 776 else:
777 777 classname = "%s.%s" % \
778 778 (self.__class__.__module__, self.__class__.__name__)
779 779 if mode == "header" or mode == "footer":
780 780 yield (astyle.style_error, "%s: %s" % (classname, self))
781 781 else:
782 782 yield (astyle.style_error, classname)
783 783 xrepr.when_type(Exception)(xrepr_exception)
784 784
785 785
786 786 def xrepr_listtuple(self, mode="default"):
787 787 if mode == "header" or mode == "footer":
788 788 if self.__class__.__module__ == "__builtin__":
789 789 classname = self.__class__.__name__
790 790 else:
791 791 classname = "%s.%s" % \
792 792 (self.__class__.__module__,self.__class__.__name__)
793 793 yield (astyle.style_default,
794 794 "<%s object with %d items at 0x%x>" % \
795 795 (classname, len(self), id(self)))
796 796 else:
797 797 yield (-1, False)
798 798 if isinstance(self, list):
799 799 yield (astyle.style_default, "[")
800 800 end = "]"
801 801 else:
802 802 yield (astyle.style_default, "(")
803 803 end = ")"
804 804 for (i, subself) in enumerate(self):
805 805 if i:
806 806 yield (astyle.style_default, ", ")
807 807 for part in xrepr(subself, "default"):
808 808 yield part
809 809 yield (astyle.style_default, end)
810 810 xrepr.when_type(list)(xrepr_listtuple)
811 811 xrepr.when_type(tuple)(xrepr_listtuple)
812 812
813 813
814 814 def xrepr_dict(self, mode="default"):
815 815 if mode == "header" or mode == "footer":
816 816 if self.__class__.__module__ == "__builtin__":
817 817 classname = self.__class__.__name__
818 818 else:
819 819 classname = "%s.%s" % \
820 820 (self.__class__.__module__,self.__class__.__name__)
821 821 yield (astyle.style_default,
822 822 "<%s object with %d items at 0x%x>" % \
823 823 (classname, len(self), id(self)))
824 824 else:
825 825 yield (-1, False)
826 826 if isinstance(self, dict):
827 827 yield (astyle.style_default, "{")
828 828 end = "}"
829 829 else:
830 830 yield (astyle.style_default, "dictproxy((")
831 831 end = "})"
832 832 for (i, (key, value)) in enumerate(self.iteritems()):
833 833 if i:
834 834 yield (astyle.style_default, ", ")
835 835 for part in xrepr(key, "default"):
836 836 yield part
837 837 yield (astyle.style_default, ": ")
838 838 for part in xrepr(value, "default"):
839 839 yield part
840 840 yield (astyle.style_default, end)
841 841 xrepr.when_type(dict)(xrepr_dict)
842 842 xrepr.when_type(types.DictProxyType)(xrepr_dict)
843 843
844 844
845 845 def upgradexattr(attr):
846 846 """
847 847 Convert an attribute descriptor string to a real descriptor object.
848 848
849 849 If attr already is a descriptor object return it unmodified. A
850 850 ``SelfDescriptor`` will be returned if ``attr`` is ``None``. ``"foo"``
851 851 returns an ``AttributeDescriptor`` for the attribute named ``"foo"``.
852 852 ``"foo()"`` returns a ``MethodDescriptor`` for the method named ``"foo"``.
853 853 ``"-foo"`` will return an ``IterAttributeDescriptor`` for the attribute
854 854 named ``"foo"`` and ``"-foo()"`` will return an ``IterMethodDescriptor``
855 855 for the method named ``"foo"``. Furthermore integers will return the appropriate
856 856 ``IndexDescriptor`` and callables will return a ``FunctionDescriptor``.
857 857 """
858 858 if attr is None:
859 859 return selfdescriptor
860 860 elif isinstance(attr, Descriptor):
861 861 return attr
862 862 elif isinstance(attr, basestring):
863 863 if attr.endswith("()"):
864 864 if attr.startswith("-"):
865 865 return IterMethodDescriptor(attr[1:-2])
866 866 else:
867 867 return MethodDescriptor(attr[:-2])
868 868 else:
869 869 if attr.startswith("-"):
870 870 return IterAttributeDescriptor(attr[1:])
871 871 else:
872 872 return AttributeDescriptor(attr)
873 873 elif isinstance(attr, (int, long)):
874 874 return IndexDescriptor(attr)
875 875 elif callable(attr):
876 876 return FunctionDescriptor(attr)
877 877 else:
878 878 raise TypeError("can't handle descriptor %r" % attr)
879 879
880 880
881 881 def xattrs(item, mode="default"):
882 882 """
883 883 Generic function that returns an iterable of attribute descriptors
884 884 to be used for displaying the attributes ob the object ``item`` in display
885 885 mode ``mode``.
886 886
887 887 There are two possible modes:
888 888
889 889 ``"detail"``
890 890 The ``Display`` object wants to display a detailed list of the object
891 891 attributes.
892 892
893 893 ``"default"``
894 894 The ``Display`` object wants to display the object in a list view.
895 895
896 896 If no implementation is registered for the object ``item`` ``xattrs`` falls
897 897 back to trying the ``__xattrs__`` method of the object. If this doesn't
898 898 exist either, ``dir(item)`` is used for ``"detail"`` mode and ``(None,)``
899 899 for ``"default"`` mode.
900 900
901 901 The implementation must yield attribute descriptors (see the class
902 902 ``Descriptor`` for more info). The ``__xattrs__`` method may also return
903 903 attribute descriptor strings (and ``None``) which will be converted to real
904 904 descriptors by ``upgradexattr()``.
905 905 """
906 906 try:
907 907 func = item.__xattrs__
908 908 except AttributeError:
909 909 if mode == "detail":
910 910 for attrname in dir(item):
911 911 yield AttributeDescriptor(attrname)
912 912 else:
913 913 yield selfdescriptor
914 914 else:
915 915 for attr in func(mode):
916 916 yield upgradexattr(attr)
917 917 xattrs = simplegeneric.generic(xattrs)
918 918
919 919
920 920 def xattrs_complex(self, mode="default"):
921 921 if mode == "detail":
922 922 return (AttributeDescriptor("real"), AttributeDescriptor("imag"))
923 923 return (selfdescriptor,)
924 924 xattrs.when_type(complex)(xattrs_complex)
925 925
926 926
927 927 def _isdict(item):
928 928 try:
929 929 itermeth = item.__class__.__iter__
930 930 except (AttributeError, TypeError):
931 931 return False
932 932 return itermeth is dict.__iter__ or itermeth is types.DictProxyType.__iter__
933 933
934 934
935 935 def _isstr(item):
936 936 if not isinstance(item, basestring):
937 937 return False
938 938 try:
939 939 itermeth = item.__class__.__iter__
940 940 except AttributeError:
941 941 return True
942 942 return False # ``__iter__`` has been redefined
943 943
944 944
945 945 def xiter(item):
946 946 """
947 947 Generic function that implements iteration for pipeline expression. If no
948 948 implementation is registered for ``item`` ``xiter`` falls back to ``iter``.
949 949 """
950 950 try:
951 951 func = item.__xiter__
952 952 except AttributeError:
953 953 if _isdict(item):
954 954 def items(item):
955 955 fields = ("key", "value")
956 956 for (key, value) in item.iteritems():
957 957 yield Fields(fields, key=key, value=value)
958 958 return items(item)
959 959 elif isinstance(item, new.module):
960 960 def items(item):
961 961 fields = ("key", "value")
962 962 for key in sorted(item.__dict__):
963 963 yield Fields(fields, key=key, value=getattr(item, key))
964 964 return items(item)
965 965 elif _isstr(item):
966 966 if not item:
967 967 raise ValueError("can't enter empty string")
968 968 lines = item.splitlines()
969 969 if len(lines) == 1:
970 970 def iterone(item):
971 971 yield item
972 972 return iterone(item)
973 973 else:
974 974 return iter(lines)
975 975 return iter(item)
976 976 else:
977 977 return iter(func()) # iter() just to be safe
978 978 xiter = simplegeneric.generic(xiter)
979 979
980 980
981 981 class ichain(Pipe):
982 982 """
983 983 Chains multiple ``Table``s into one.
984 984 """
985 985
986 986 def __init__(self, *iters):
987 987 self.iters = iters
988 988
989 989 def __iter__(self):
990 990 return itertools.chain(*self.iters)
991 991
992 992 def __xrepr__(self, mode="default"):
993 993 if mode == "header" or mode == "footer":
994 994 for (i, item) in enumerate(self.iters):
995 995 if i:
996 996 yield (astyle.style_default, "+")
997 997 if isinstance(item, Pipe):
998 998 yield (astyle.style_default, "(")
999 999 for part in xrepr(item, mode):
1000 1000 yield part
1001 1001 if isinstance(item, Pipe):
1002 1002 yield (astyle.style_default, ")")
1003 1003 else:
1004 1004 yield (astyle.style_default, repr(self))
1005 1005
1006 1006 def __repr__(self):
1007 1007 args = ", ".join([repr(it) for it in self.iters])
1008 1008 return "%s.%s(%s)" % \
1009 1009 (self.__class__.__module__, self.__class__.__name__, args)
1010 1010
1011 1011
1012 1012 class ifile(path.path):
1013 1013 """
1014 1014 file (or directory) object.
1015 1015 """
1016 1016
1017 1017 def getmode(self):
1018 1018 return self.stat().st_mode
1019 1019 mode = property(getmode, None, None, "Access mode")
1020 1020
1021 1021 def gettype(self):
1022 1022 data = [
1023 1023 (stat.S_ISREG, "file"),
1024 1024 (stat.S_ISDIR, "dir"),
1025 1025 (stat.S_ISCHR, "chardev"),
1026 1026 (stat.S_ISBLK, "blockdev"),
1027 1027 (stat.S_ISFIFO, "fifo"),
1028 1028 (stat.S_ISLNK, "symlink"),
1029 1029 (stat.S_ISSOCK,"socket"),
1030 1030 ]
1031 1031 lstat = self.lstat()
1032 1032 if lstat is not None:
1033 1033 types = set([text for (func, text) in data if func(lstat.st_mode)])
1034 1034 else:
1035 1035 types = set()
1036 1036 m = self.mode
1037 1037 types.update([text for (func, text) in data if func(m)])
1038 1038 return ", ".join(types)
1039 1039 type = property(gettype, None, None, "file type (file, directory, link, etc.)")
1040 1040
1041 1041 def getmodestr(self):
1042 1042 m = self.mode
1043 1043 data = [
1044 1044 (stat.S_IRUSR, "-r"),
1045 1045 (stat.S_IWUSR, "-w"),
1046 1046 (stat.S_IXUSR, "-x"),
1047 1047 (stat.S_IRGRP, "-r"),
1048 1048 (stat.S_IWGRP, "-w"),
1049 1049 (stat.S_IXGRP, "-x"),
1050 1050 (stat.S_IROTH, "-r"),
1051 1051 (stat.S_IWOTH, "-w"),
1052 1052 (stat.S_IXOTH, "-x"),
1053 1053 ]
1054 1054 return "".join([text[bool(m&bit)] for (bit, text) in data])
1055 1055
1056 1056 modestr = property(getmodestr, None, None, "Access mode as string")
1057 1057
1058 1058 def getblocks(self):
1059 1059 return self.stat().st_blocks
1060 1060 blocks = property(getblocks, None, None, "File size in blocks")
1061 1061
1062 1062 def getblksize(self):
1063 1063 return self.stat().st_blksize
1064 1064 blksize = property(getblksize, None, None, "Filesystem block size")
1065 1065
1066 1066 def getdev(self):
1067 1067 return self.stat().st_dev
1068 1068 dev = property(getdev)
1069 1069
1070 1070 def getnlink(self):
1071 1071 return self.stat().st_nlink
1072 1072 nlink = property(getnlink, None, None, "Number of links")
1073 1073
1074 1074 def getuid(self):
1075 1075 return self.stat().st_uid
1076 1076 uid = property(getuid, None, None, "User id of file owner")
1077 1077
1078 1078 def getgid(self):
1079 1079 return self.stat().st_gid
1080 1080 gid = property(getgid, None, None, "Group id of file owner")
1081 1081
1082 1082 def getowner(self):
1083 1083 stat = self.stat()
1084 1084 try:
1085 1085 return pwd.getpwuid(stat.st_uid).pw_name
1086 1086 except KeyError:
1087 1087 return stat.st_uid
1088 1088 owner = property(getowner, None, None, "Owner name (or id)")
1089 1089
1090 1090 def getgroup(self):
1091 1091 stat = self.stat()
1092 1092 try:
1093 1093 return grp.getgrgid(stat.st_gid).gr_name
1094 1094 except KeyError:
1095 1095 return stat.st_gid
1096 1096 group = property(getgroup, None, None, "Group name (or id)")
1097 1097
1098 1098 def getadate(self):
1099 1099 return datetime.datetime.utcfromtimestamp(self.atime)
1100 1100 adate = property(getadate, None, None, "Access date")
1101 1101
1102 1102 def getcdate(self):
1103 1103 return datetime.datetime.utcfromtimestamp(self.ctime)
1104 1104 cdate = property(getcdate, None, None, "Creation date")
1105 1105
1106 1106 def getmdate(self):
1107 1107 return datetime.datetime.utcfromtimestamp(self.mtime)
1108 1108 mdate = property(getmdate, None, None, "Modification date")
1109 1109
1110 1110 def mimetype(self):
1111 1111 """
1112 1112 Return MIME type guessed from the extension.
1113 1113 """
1114 1114 return mimetypes.guess_type(self.basename())[0]
1115 1115
1116 1116 def encoding(self):
1117 1117 """
1118 1118 Return guessed compression (like "compress" or "gzip").
1119 1119 """
1120 1120 return mimetypes.guess_type(self.basename())[1]
1121 1121
1122 1122 def __repr__(self):
1123 1123 return "ifile(%s)" % path._base.__repr__(self)
1124 1124
1125 1125 if sys.platform == "win32":
1126 1126 defaultattrs = (None, "type", "size", "modestr", "mdate")
1127 1127 else:
1128 1128 defaultattrs = (None, "type", "size", "modestr", "owner", "group", "mdate")
1129 1129
1130 1130 def __xattrs__(self, mode="default"):
1131 1131 if mode == "detail":
1132 1132 return (
1133 1133 "name",
1134 1134 "basename()",
1135 1135 "abspath()",
1136 1136 "realpath()",
1137 1137 "type",
1138 1138 "mode",
1139 1139 "modestr",
1140 1140 "stat()",
1141 1141 "lstat()",
1142 1142 "uid",
1143 1143 "gid",
1144 1144 "owner",
1145 1145 "group",
1146 1146 "dev",
1147 1147 "nlink",
1148 1148 "ctime",
1149 1149 "mtime",
1150 1150 "atime",
1151 1151 "cdate",
1152 1152 "mdate",
1153 1153 "adate",
1154 1154 "size",
1155 1155 "blocks",
1156 1156 "blksize",
1157 1157 "isdir()",
1158 1158 "islink()",
1159 1159 "mimetype()",
1160 1160 "encoding()",
1161 1161 "-listdir()",
1162 1162 "-dirs()",
1163 1163 "-files()",
1164 1164 "-walk()",
1165 1165 "-walkdirs()",
1166 1166 "-walkfiles()",
1167 1167 )
1168 1168 else:
1169 1169 return self.defaultattrs
1170 1170
1171 1171
1172 1172 def xiter_ifile(self):
1173 1173 if self.isdir():
1174 1174 yield (self / os.pardir).abspath()
1175 1175 for child in sorted(self.listdir()):
1176 1176 yield child
1177 1177 else:
1178 1178 f = self.open("rb")
1179 1179 for line in f:
1180 1180 yield line
1181 1181 f.close()
1182 1182 xiter.when_type(ifile)(xiter_ifile)
1183 1183
1184 1184
1185 1185 # We need to implement ``xrepr`` for ``ifile`` as a generic function, because
1186 1186 # otherwise ``xrepr_str`` would kick in.
1187 1187 def xrepr_ifile(self, mode="default"):
1188 1188 try:
1189 1189 if self.isdir():
1190 1190 name = "idir"
1191 1191 style = astyle.style_dir
1192 1192 else:
1193 1193 name = "ifile"
1194 1194 style = astyle.style_file
1195 1195 except IOError:
1196 1196 name = "ifile"
1197 1197 style = astyle.style_default
1198 1198 if mode in ("cell", "header", "footer"):
1199 1199 abspath = repr(path._base(self.normpath()))
1200 1200 if abspath.startswith("u"):
1201 1201 abspath = abspath[2:-1]
1202 1202 else:
1203 1203 abspath = abspath[1:-1]
1204 1204 if mode == "cell":
1205 1205 yield (style, abspath)
1206 1206 else:
1207 1207 yield (style, "%s(%s)" % (name, abspath))
1208 1208 else:
1209 1209 yield (style, repr(self))
1210 1210 xrepr.when_type(ifile)(xrepr_ifile)
1211 1211
1212 1212
1213 1213 class ils(Table):
1214 1214 """
1215 1215 List the current (or a specified) directory.
1216 1216
1217 1217 Examples::
1218 1218
1219 1219 >>> ils
1220 1220 <class 'IPython.extensions.ipipe.ils'>
1221 1221 >>> ils("/usr/local/lib/python2.4")
1222 1222 IPython.extensions.ipipe.ils('/usr/local/lib/python2.4')
1223 1223 >>> ils("~")
1224 1224 IPython.extensions.ipipe.ils('/home/fperez')
1225 1225 # all-random
1226 1226 """
1227 1227 def __init__(self, base=os.curdir, dirs=True, files=True):
1228 1228 self.base = os.path.expanduser(base)
1229 1229 self.dirs = dirs
1230 1230 self.files = files
1231 1231
1232 1232 def __iter__(self):
1233 1233 base = ifile(self.base)
1234 1234 yield (base / os.pardir).abspath()
1235 1235 for child in sorted(base.listdir()):
1236 1236 if self.dirs:
1237 1237 if self.files:
1238 1238 yield child
1239 1239 else:
1240 1240 if child.isdir():
1241 1241 yield child
1242 1242 elif self.files:
1243 1243 if not child.isdir():
1244 1244 yield child
1245 1245
1246 1246 def __xrepr__(self, mode="default"):
1247 1247 return xrepr(ifile(self.base), mode)
1248 1248
1249 1249 def __repr__(self):
1250 1250 return "%s.%s(%r)" % \
1251 1251 (self.__class__.__module__, self.__class__.__name__, self.base)
1252 1252
1253 1253
1254 1254 class iglob(Table):
1255 1255 """
1256 1256 List all files and directories matching a specified pattern.
1257 1257 (See ``glob.glob()`` for more info.).
1258 1258
1259 1259 Examples::
1260 1260
1261 1261 >>> iglob("*.py")
1262 1262 IPython.extensions.ipipe.iglob('*.py')
1263 1263 """
1264 1264 def __init__(self, glob):
1265 1265 self.glob = glob
1266 1266
1267 1267 def __iter__(self):
1268 1268 for name in glob.glob(self.glob):
1269 1269 yield ifile(name)
1270 1270
1271 1271 def __xrepr__(self, mode="default"):
1272 1272 if mode == "header" or mode == "footer" or mode == "cell":
1273 1273 yield (astyle.style_default,
1274 1274 "%s(%r)" % (self.__class__.__name__, self.glob))
1275 1275 else:
1276 1276 yield (astyle.style_default, repr(self))
1277 1277
1278 1278 def __repr__(self):
1279 1279 return "%s.%s(%r)" % \
1280 1280 (self.__class__.__module__, self.__class__.__name__, self.glob)
1281 1281
1282 1282
1283 1283 class iwalk(Table):
1284 1284 """
1285 1285 List all files and directories in a directory and it's subdirectory::
1286 1286
1287 1287 >>> iwalk
1288 1288 <class 'IPython.extensions.ipipe.iwalk'>
1289 1289 >>> iwalk("/usr/lib")
1290 1290 IPython.extensions.ipipe.iwalk('/usr/lib')
1291 1291 >>> iwalk("~")
1292 1292 IPython.extensions.ipipe.iwalk('/home/fperez') # random
1293 1293
1294 1294 """
1295 1295 def __init__(self, base=os.curdir, dirs=True, files=True):
1296 1296 self.base = os.path.expanduser(base)
1297 1297 self.dirs = dirs
1298 1298 self.files = files
1299 1299
1300 1300 def __iter__(self):
1301 1301 for (dirpath, dirnames, filenames) in os.walk(self.base):
1302 1302 if self.dirs:
1303 1303 for name in sorted(dirnames):
1304 1304 yield ifile(os.path.join(dirpath, name))
1305 1305 if self.files:
1306 1306 for name in sorted(filenames):
1307 1307 yield ifile(os.path.join(dirpath, name))
1308 1308
1309 1309 def __xrepr__(self, mode="default"):
1310 1310 if mode == "header" or mode == "footer" or mode == "cell":
1311 1311 yield (astyle.style_default,
1312 1312 "%s(%r)" % (self.__class__.__name__, self.base))
1313 1313 else:
1314 1314 yield (astyle.style_default, repr(self))
1315 1315
1316 1316 def __repr__(self):
1317 1317 return "%s.%s(%r)" % \
1318 1318 (self.__class__.__module__, self.__class__.__name__, self.base)
1319 1319
1320 1320
1321 1321 class ipwdentry(object):
1322 1322 """
1323 1323 ``ipwdentry`` objects encapsulate entries in the Unix user account and
1324 1324 password database.
1325 1325 """
1326 1326 def __init__(self, id):
1327 1327 self._id = id
1328 1328 self._entry = None
1329 1329
1330 1330 def __eq__(self, other):
1331 1331 return self.__class__ is other.__class__ and self._id == other._id
1332 1332
1333 1333 def __ne__(self, other):
1334 1334 return self.__class__ is not other.__class__ or self._id != other._id
1335 1335
1336 1336 def _getentry(self):
1337 1337 if self._entry is None:
1338 1338 if isinstance(self._id, basestring):
1339 1339 self._entry = pwd.getpwnam(self._id)
1340 1340 else:
1341 1341 self._entry = pwd.getpwuid(self._id)
1342 1342 return self._entry
1343 1343
1344 1344 def getname(self):
1345 1345 if isinstance(self._id, basestring):
1346 1346 return self._id
1347 1347 else:
1348 1348 return self._getentry().pw_name
1349 1349 name = property(getname, None, None, "User name")
1350 1350
1351 1351 def getpasswd(self):
1352 1352 return self._getentry().pw_passwd
1353 1353 passwd = property(getpasswd, None, None, "Password")
1354 1354
1355 1355 def getuid(self):
1356 1356 if isinstance(self._id, basestring):
1357 1357 return self._getentry().pw_uid
1358 1358 else:
1359 1359 return self._id
1360 1360 uid = property(getuid, None, None, "User id")
1361 1361
1362 1362 def getgid(self):
1363 1363 return self._getentry().pw_gid
1364 1364 gid = property(getgid, None, None, "Primary group id")
1365 1365
1366 1366 def getgroup(self):
1367 1367 return igrpentry(self.gid)
1368 1368 group = property(getgroup, None, None, "Group")
1369 1369
1370 1370 def getgecos(self):
1371 1371 return self._getentry().pw_gecos
1372 1372 gecos = property(getgecos, None, None, "Information (e.g. full user name)")
1373 1373
1374 1374 def getdir(self):
1375 1375 return self._getentry().pw_dir
1376 1376 dir = property(getdir, None, None, "$HOME directory")
1377 1377
1378 1378 def getshell(self):
1379 1379 return self._getentry().pw_shell
1380 1380 shell = property(getshell, None, None, "Login shell")
1381 1381
1382 1382 def __xattrs__(self, mode="default"):
1383 1383 return ("name", "passwd", "uid", "gid", "gecos", "dir", "shell")
1384 1384
1385 1385 def __repr__(self):
1386 1386 return "%s.%s(%r)" % \
1387 1387 (self.__class__.__module__, self.__class__.__name__, self._id)
1388 1388
1389 1389
1390 1390 class ipwd(Table):
1391 1391 """
1392 1392 List all entries in the Unix user account and password database.
1393 1393
1394 1394 Example::
1395 1395
1396 1396 >>> ipwd | isort("uid")
1397 1397 <IPython.extensions.ipipe.isort key='uid' reverse=False at 0x849efec>
1398 1398 # random
1399 1399 """
1400 1400 def __iter__(self):
1401 1401 for entry in pwd.getpwall():
1402 1402 yield ipwdentry(entry.pw_name)
1403 1403
1404 1404 def __xrepr__(self, mode="default"):
1405 1405 if mode == "header" or mode == "footer" or mode == "cell":
1406 1406 yield (astyle.style_default, "%s()" % self.__class__.__name__)
1407 1407 else:
1408 1408 yield (astyle.style_default, repr(self))
1409 1409
1410 1410
1411 1411 class igrpentry(object):
1412 1412 """
1413 1413 ``igrpentry`` objects encapsulate entries in the Unix group database.
1414 1414 """
1415 1415 def __init__(self, id):
1416 1416 self._id = id
1417 1417 self._entry = None
1418 1418
1419 1419 def __eq__(self, other):
1420 1420 return self.__class__ is other.__class__ and self._id == other._id
1421 1421
1422 1422 def __ne__(self, other):
1423 1423 return self.__class__ is not other.__class__ or self._id != other._id
1424 1424
1425 1425 def _getentry(self):
1426 1426 if self._entry is None:
1427 1427 if isinstance(self._id, basestring):
1428 1428 self._entry = grp.getgrnam(self._id)
1429 1429 else:
1430 1430 self._entry = grp.getgrgid(self._id)
1431 1431 return self._entry
1432 1432
1433 1433 def getname(self):
1434 1434 if isinstance(self._id, basestring):
1435 1435 return self._id
1436 1436 else:
1437 1437 return self._getentry().gr_name
1438 1438 name = property(getname, None, None, "Group name")
1439 1439
1440 1440 def getpasswd(self):
1441 1441 return self._getentry().gr_passwd
1442 1442 passwd = property(getpasswd, None, None, "Password")
1443 1443
1444 1444 def getgid(self):
1445 1445 if isinstance(self._id, basestring):
1446 1446 return self._getentry().gr_gid
1447 1447 else:
1448 1448 return self._id
1449 1449 gid = property(getgid, None, None, "Group id")
1450 1450
1451 1451 def getmem(self):
1452 1452 return self._getentry().gr_mem
1453 1453 mem = property(getmem, None, None, "Members")
1454 1454
1455 1455 def __xattrs__(self, mode="default"):
1456 1456 return ("name", "passwd", "gid", "mem")
1457 1457
1458 1458 def __xrepr__(self, mode="default"):
1459 1459 if mode == "header" or mode == "footer" or mode == "cell":
1460 1460 yield (astyle.style_default, "group ")
1461 1461 try:
1462 1462 yield (astyle.style_default, self.name)
1463 1463 except KeyError:
1464 1464 if isinstance(self._id, basestring):
1465 1465 yield (astyle.style_default, self.name_id)
1466 1466 else:
1467 1467 yield (astyle.style_type_number, str(self._id))
1468 1468 else:
1469 1469 yield (astyle.style_default, repr(self))
1470 1470
1471 1471 def __iter__(self):
1472 1472 for member in self.mem:
1473 1473 yield ipwdentry(member)
1474 1474
1475 1475 def __repr__(self):
1476 1476 return "%s.%s(%r)" % \
1477 1477 (self.__class__.__module__, self.__class__.__name__, self._id)
1478 1478
1479 1479
1480 1480 class igrp(Table):
1481 1481 """
1482 1482 This ``Table`` lists all entries in the Unix group database.
1483 1483 """
1484 1484 def __iter__(self):
1485 1485 for entry in grp.getgrall():
1486 1486 yield igrpentry(entry.gr_name)
1487 1487
1488 1488 def __xrepr__(self, mode="default"):
1489 1489 if mode == "header" or mode == "footer":
1490 1490 yield (astyle.style_default, "%s()" % self.__class__.__name__)
1491 1491 else:
1492 1492 yield (astyle.style_default, repr(self))
1493 1493
1494 1494
1495 1495 class Fields(object):
1496 1496 def __init__(self, fieldnames, **fields):
1497 1497 self.__fieldnames = [upgradexattr(fieldname) for fieldname in fieldnames]
1498 1498 for (key, value) in fields.iteritems():
1499 1499 setattr(self, key, value)
1500 1500
1501 1501 def __xattrs__(self, mode="default"):
1502 1502 return self.__fieldnames
1503 1503
1504 1504 def __xrepr__(self, mode="default"):
1505 1505 yield (-1, False)
1506 1506 if mode == "header" or mode == "cell":
1507 1507 yield (astyle.style_default, self.__class__.__name__)
1508 1508 yield (astyle.style_default, "(")
1509 1509 for (i, f) in enumerate(self.__fieldnames):
1510 1510 if i:
1511 1511 yield (astyle.style_default, ", ")
1512 1512 yield (astyle.style_default, f.name())
1513 1513 yield (astyle.style_default, "=")
1514 1514 for part in xrepr(getattr(self, f), "default"):
1515 1515 yield part
1516 1516 yield (astyle.style_default, ")")
1517 1517 elif mode == "footer":
1518 1518 yield (astyle.style_default, self.__class__.__name__)
1519 1519 yield (astyle.style_default, "(")
1520 1520 for (i, f) in enumerate(self.__fieldnames):
1521 1521 if i:
1522 1522 yield (astyle.style_default, ", ")
1523 1523 yield (astyle.style_default, f.name())
1524 1524 yield (astyle.style_default, ")")
1525 1525 else:
1526 1526 yield (astyle.style_default, repr(self))
1527 1527
1528 1528
1529 1529 class FieldTable(Table, list):
1530 1530 def __init__(self, *fields):
1531 1531 Table.__init__(self)
1532 1532 list.__init__(self)
1533 1533 self.fields = fields
1534 1534
1535 1535 def add(self, **fields):
1536 1536 self.append(Fields(self.fields, **fields))
1537 1537
1538 1538 def __xrepr__(self, mode="default"):
1539 1539 yield (-1, False)
1540 1540 if mode == "header" or mode == "footer":
1541 1541 yield (astyle.style_default, self.__class__.__name__)
1542 1542 yield (astyle.style_default, "(")
1543 1543 for (i, f) in enumerate(self.__fieldnames):
1544 1544 if i:
1545 1545 yield (astyle.style_default, ", ")
1546 1546 yield (astyle.style_default, f)
1547 1547 yield (astyle.style_default, ")")
1548 1548 else:
1549 1549 yield (astyle.style_default, repr(self))
1550 1550
1551 1551 def __repr__(self):
1552 1552 return "<%s.%s object with fields=%r at 0x%x>" % \
1553 1553 (self.__class__.__module__, self.__class__.__name__,
1554 1554 ", ".join(map(repr, self.fields)), id(self))
1555 1555
1556 1556
1557 1557 class List(list):
1558 1558 def __xattrs__(self, mode="default"):
1559 1559 return xrange(len(self))
1560 1560
1561 1561 def __xrepr__(self, mode="default"):
1562 1562 yield (-1, False)
1563 1563 if mode == "header" or mode == "cell" or mode == "footer" or mode == "default":
1564 1564 yield (astyle.style_default, self.__class__.__name__)
1565 1565 yield (astyle.style_default, "(")
1566 1566 for (i, item) in enumerate(self):
1567 1567 if i:
1568 1568 yield (astyle.style_default, ", ")
1569 1569 for part in xrepr(item, "default"):
1570 1570 yield part
1571 1571 yield (astyle.style_default, ")")
1572 1572 else:
1573 1573 yield (astyle.style_default, repr(self))
1574 1574
1575 1575
1576 1576 class ienv(Table):
1577 1577 """
1578 1578 List environment variables.
1579 1579
1580 1580 Example::
1581 1581
1582 1582 >>> ienv
1583 1583 <class 'IPython.extensions.ipipe.ienv'>
1584 1584 """
1585 1585
1586 1586 def __iter__(self):
1587 1587 fields = ("key", "value")
1588 1588 for (key, value) in os.environ.iteritems():
1589 1589 yield Fields(fields, key=key, value=value)
1590 1590
1591 1591 def __xrepr__(self, mode="default"):
1592 1592 if mode == "header" or mode == "cell":
1593 1593 yield (astyle.style_default, "%s()" % self.__class__.__name__)
1594 1594 else:
1595 1595 yield (astyle.style_default, repr(self))
1596 1596
1597 1597
1598 1598 class ihist(Table):
1599 1599 """
1600 1600 IPython input history
1601 1601
1602 1602 Example::
1603 1603
1604 1604 >>> ihist
1605 1605 <class 'IPython.extensions.ipipe.ihist'>
1606 1606 >>> ihist(True) # raw mode
1607 1607 <IPython.extensions.ipipe.ihist object at 0x849602c> # random
1608 1608 """
1609 1609 def __init__(self, raw=True):
1610 1610 self.raw = raw
1611 1611
1612 1612 def __iter__(self):
1613 1613 api = ipapi.get()
1614 1614 if self.raw:
1615 1615 for line in api.input_hist_raw:
1616 1616 yield line.rstrip("\n")
1617 1617 else:
1618 1618 for line in api.input_hist:
1619 1619 yield line.rstrip("\n")
1620 1620
1621 1621
1622 1622 class Alias(object):
1623 1623 """
1624 1624 Entry in the alias table
1625 1625 """
1626 1626 def __init__(self, name, args, command):
1627 1627 self.name = name
1628 1628 self.args = args
1629 1629 self.command = command
1630 1630
1631 1631 def __xattrs__(self, mode="default"):
1632 1632 return ("name", "args", "command")
1633 1633
1634 1634
1635 1635 class ialias(Table):
1636 1636 """
1637 1637 IPython alias list
1638 1638
1639 1639 Example::
1640 1640
1641 1641 >>> ialias
1642 1642 <class 'IPython.extensions.ipipe.ialias'>
1643 1643 """
1644 1644 def __iter__(self):
1645 1645 api = ipapi.get()
1646 1646
1647 1647 for (name, (args, command)) in api.alias_manager.alias_table.iteritems():
1648 1648 yield Alias(name, args, command)
1649 1649
1650 1650
1651 1651 class icsv(Pipe):
1652 1652 """
1653 1653 This ``Pipe`` turns the input (with must be a pipe outputting lines
1654 1654 or an ``ifile``) into lines of CVS columns.
1655 1655 """
1656 1656 def __init__(self, **csvargs):
1657 1657 """
1658 1658 Create an ``icsv`` object. ``cvsargs`` will be passed through as
1659 1659 keyword arguments to ``cvs.reader()``.
1660 1660 """
1661 1661 self.csvargs = csvargs
1662 1662
1663 1663 def __iter__(self):
1664 1664 input = self.input
1665 1665 if isinstance(input, ifile):
1666 1666 input = input.open("rb")
1667 1667 reader = csv.reader(input, **self.csvargs)
1668 1668 for line in reader:
1669 1669 yield List(line)
1670 1670
1671 1671 def __xrepr__(self, mode="default"):
1672 1672 yield (-1, False)
1673 1673 if mode == "header" or mode == "footer":
1674 1674 input = getattr(self, "input", None)
1675 1675 if input is not None:
1676 1676 for part in xrepr(input, mode):
1677 1677 yield part
1678 1678 yield (astyle.style_default, " | ")
1679 1679 yield (astyle.style_default, "%s(" % self.__class__.__name__)
1680 1680 for (i, (name, value)) in enumerate(self.csvargs.iteritems()):
1681 1681 if i:
1682 1682 yield (astyle.style_default, ", ")
1683 1683 yield (astyle.style_default, name)
1684 1684 yield (astyle.style_default, "=")
1685 1685 for part in xrepr(value, "default"):
1686 1686 yield part
1687 1687 yield (astyle.style_default, ")")
1688 1688 else:
1689 1689 yield (astyle.style_default, repr(self))
1690 1690
1691 1691 def __repr__(self):
1692 1692 args = ", ".join(["%s=%r" % item for item in self.csvargs.iteritems()])
1693 1693 return "<%s.%s %s at 0x%x>" % \
1694 1694 (self.__class__.__module__, self.__class__.__name__, args, id(self))
1695 1695
1696 1696
1697 1697 class ix(Table):
1698 1698 """
1699 1699 Execute a system command and list its output as lines
1700 1700 (similar to ``os.popen()``).
1701 1701
1702 1702 Examples::
1703 1703
1704 1704 >>> ix("ps x")
1705 1705 IPython.extensions.ipipe.ix('ps x')
1706 1706
1707 1707 >>> ix("find .") | ifile
1708 1708 <IPython.extensions.ipipe.ieval expr=<class 'IPython.extensions.ipipe.ifile'> at 0x8509d2c>
1709 1709 # random
1710 1710 """
1711 1711 def __init__(self, cmd):
1712 1712 self.cmd = cmd
1713 1713 self._pipeout = None
1714 1714
1715 1715 def __iter__(self):
1716 1716 (_pipein, self._pipeout) = os.popen4(self.cmd)
1717 1717 _pipein.close()
1718 1718 for l in self._pipeout:
1719 1719 yield l.rstrip("\r\n")
1720 1720 self._pipeout.close()
1721 1721 self._pipeout = None
1722 1722
1723 1723 def __del__(self):
1724 1724 if self._pipeout is not None and not self._pipeout.closed:
1725 1725 self._pipeout.close()
1726 1726 self._pipeout = None
1727 1727
1728 1728 def __xrepr__(self, mode="default"):
1729 1729 if mode == "header" or mode == "footer":
1730 1730 yield (astyle.style_default,
1731 1731 "%s(%r)" % (self.__class__.__name__, self.cmd))
1732 1732 else:
1733 1733 yield (astyle.style_default, repr(self))
1734 1734
1735 1735 def __repr__(self):
1736 1736 return "%s.%s(%r)" % \
1737 1737 (self.__class__.__module__, self.__class__.__name__, self.cmd)
1738 1738
1739 1739
1740 1740 class ifilter(Pipe):
1741 1741 """
1742 1742 Filter an input pipe. Only objects where an expression evaluates to true
1743 1743 (and doesn't raise an exception) are listed.
1744 1744
1745 1745 Examples::
1746 1746
1747 1747 >>> ils | ifilter("_.isfile() and size>1000")
1748 1748 >>> igrp | ifilter("len(mem)")
1749 1749 >>> sys.modules | ifilter(lambda _:_.value is not None)
1750 1750 # all-random
1751 1751 """
1752 1752
1753 1753 def __init__(self, expr, globals=None, errors="raiseifallfail"):
1754 1754 """
1755 1755 Create an ``ifilter`` object. ``expr`` can be a callable or a string
1756 1756 containing an expression. ``globals`` will be used as the global
1757 1757 namespace for calling string expressions (defaulting to IPython's
1758 1758 user namespace). ``errors`` specifies how exception during evaluation
1759 1759 of ``expr`` are handled:
1760 1760
1761 1761 ``"drop"``
1762 1762 drop all items that have errors;
1763 1763
1764 1764 ``"keep"``
1765 1765 keep all items that have errors;
1766 1766
1767 1767 ``"keeperror"``
1768 1768 keep the exception of all items that have errors;
1769 1769
1770 1770 ``"raise"``
1771 1771 raise the exception;
1772 1772
1773 1773 ``"raiseifallfail"``
1774 1774 raise the first exception if all items have errors; otherwise drop
1775 1775 those with errors (this is the default).
1776 1776 """
1777 1777 self.expr = expr
1778 1778 self.globals = globals
1779 1779 self.errors = errors
1780 1780
1781 1781 def __iter__(self):
1782 1782 if callable(self.expr):
1783 1783 test = self.expr
1784 1784 else:
1785 1785 g = getglobals(self.globals)
1786 1786 expr = compile(self.expr, "ipipe-expression", "eval")
1787 1787 def test(item):
1788 1788 return eval(expr, g, AttrNamespace(item))
1789 1789
1790 1790 ok = 0
1791 1791 exc_info = None
1792 1792 for item in xiter(self.input):
1793 1793 try:
1794 1794 if test(item):
1795 1795 yield item
1796 1796 ok += 1
1797 1797 except (KeyboardInterrupt, SystemExit):
1798 1798 raise
1799 1799 except Exception, exc:
1800 1800 if self.errors == "drop":
1801 1801 pass # Ignore errors
1802 1802 elif self.errors == "keep":
1803 1803 yield item
1804 1804 elif self.errors == "keeperror":
1805 1805 yield exc
1806 1806 elif self.errors == "raise":
1807 1807 raise
1808 1808 elif self.errors == "raiseifallfail":
1809 1809 if exc_info is None:
1810 1810 exc_info = sys.exc_info()
1811 1811 if not ok and exc_info is not None:
1812 1812 raise exc_info[0], exc_info[1], exc_info[2]
1813 1813
1814 1814 def __xrepr__(self, mode="default"):
1815 1815 if mode == "header" or mode == "footer":
1816 1816 input = getattr(self, "input", None)
1817 1817 if input is not None:
1818 1818 for part in xrepr(input, mode):
1819 1819 yield part
1820 1820 yield (astyle.style_default, " | ")
1821 1821 yield (astyle.style_default, "%s(" % self.__class__.__name__)
1822 1822 for part in xrepr(self.expr, "default"):
1823 1823 yield part
1824 1824 yield (astyle.style_default, ")")
1825 1825 else:
1826 1826 yield (astyle.style_default, repr(self))
1827 1827
1828 1828 def __repr__(self):
1829 1829 return "<%s.%s expr=%r at 0x%x>" % \
1830 1830 (self.__class__.__module__, self.__class__.__name__,
1831 1831 self.expr, id(self))
1832 1832
1833 1833
1834 1834 class ieval(Pipe):
1835 1835 """
1836 1836 Evaluate an expression for each object in the input pipe.
1837 1837
1838 1838 Examples::
1839 1839
1840 1840 >>> ils | ieval("_.abspath()")
1841 1841 # random
1842 1842 >>> sys.path | ieval(ifile)
1843 1843 # random
1844 1844 """
1845 1845
1846 1846 def __init__(self, expr, globals=None, errors="raiseifallfail"):
1847 1847 """
1848 1848 Create an ``ieval`` object. ``expr`` can be a callable or a string
1849 1849 containing an expression. For the meaning of ``globals`` and
1850 1850 ``errors`` see ``ifilter``.
1851 1851 """
1852 1852 self.expr = expr
1853 1853 self.globals = globals
1854 1854 self.errors = errors
1855 1855
1856 1856 def __iter__(self):
1857 1857 if callable(self.expr):
1858 1858 do = self.expr
1859 1859 else:
1860 1860 g = getglobals(self.globals)
1861 1861 expr = compile(self.expr, "ipipe-expression", "eval")
1862 1862 def do(item):
1863 1863 return eval(expr, g, AttrNamespace(item))
1864 1864
1865 1865 ok = 0
1866 1866 exc_info = None
1867 1867 for item in xiter(self.input):
1868 1868 try:
1869 1869 yield do(item)
1870 1870 except (KeyboardInterrupt, SystemExit):
1871 1871 raise
1872 1872 except Exception, exc:
1873 1873 if self.errors == "drop":
1874 1874 pass # Ignore errors
1875 1875 elif self.errors == "keep":
1876 1876 yield item
1877 1877 elif self.errors == "keeperror":
1878 1878 yield exc
1879 1879 elif self.errors == "raise":
1880 1880 raise
1881 1881 elif self.errors == "raiseifallfail":
1882 1882 if exc_info is None:
1883 1883 exc_info = sys.exc_info()
1884 1884 if not ok and exc_info is not None:
1885 1885 raise exc_info[0], exc_info[1], exc_info[2]
1886 1886
1887 1887 def __xrepr__(self, mode="default"):
1888 1888 if mode == "header" or mode == "footer":
1889 1889 input = getattr(self, "input", None)
1890 1890 if input is not None:
1891 1891 for part in xrepr(input, mode):
1892 1892 yield part
1893 1893 yield (astyle.style_default, " | ")
1894 1894 yield (astyle.style_default, "%s(" % self.__class__.__name__)
1895 1895 for part in xrepr(self.expr, "default"):
1896 1896 yield part
1897 1897 yield (astyle.style_default, ")")
1898 1898 else:
1899 1899 yield (astyle.style_default, repr(self))
1900 1900
1901 1901 def __repr__(self):
1902 1902 return "<%s.%s expr=%r at 0x%x>" % \
1903 1903 (self.__class__.__module__, self.__class__.__name__,
1904 1904 self.expr, id(self))
1905 1905
1906 1906
1907 1907 class ienum(Pipe):
1908 1908 """
1909 1909 Enumerate the input pipe (i.e. wrap each input object in an object
1910 1910 with ``index`` and ``object`` attributes).
1911 1911
1912 1912 Examples::
1913 1913
1914 1914 >>> xrange(20) | ieval("_,_*_") | ienum | ifilter("index % 2 == 0") | ieval("object")
1915 1915 """
1916 1916 skip_doctest = True
1917 1917
1918 1918 def __iter__(self):
1919 1919 fields = ("index", "object")
1920 1920 for (index, object) in enumerate(xiter(self.input)):
1921 1921 yield Fields(fields, index=index, object=object)
1922 1922
1923 1923
1924 1924 class isort(Pipe):
1925 1925 """
1926 1926 Sorts the input pipe.
1927 1927
1928 1928 Examples::
1929 1929
1930 1930 >>> ils | isort("size")
1931 1931 <IPython.extensions.ipipe.isort key='size' reverse=False at 0x849ec2c>
1932 1932 >>> ils | isort("_.isdir(), _.lower()", reverse=True)
1933 1933 <IPython.extensions.ipipe.isort key='_.isdir(), _.lower()' reverse=True at 0x849eacc>
1934 1934 # all-random
1935 1935 """
1936 1936
1937 1937 def __init__(self, key=None, globals=None, reverse=False):
1938 1938 """
1939 1939 Create an ``isort`` object. ``key`` can be a callable or a string
1940 1940 containing an expression (or ``None`` in which case the items
1941 1941 themselves will be sorted). If ``reverse`` is true the sort order
1942 1942 will be reversed. For the meaning of ``globals`` see ``ifilter``.
1943 1943 """
1944 1944 self.key = key
1945 1945 self.globals = globals
1946 1946 self.reverse = reverse
1947 1947
1948 1948 def __iter__(self):
1949 1949 if self.key is None:
1950 1950 items = sorted(xiter(self.input), reverse=self.reverse)
1951 1951 elif callable(self.key):
1952 1952 items = sorted(xiter(self.input), key=self.key, reverse=self.reverse)
1953 1953 else:
1954 1954 g = getglobals(self.globals)
1955 1955 key = compile(self.key, "ipipe-expression", "eval")
1956 1956 def realkey(item):
1957 1957 return eval(key, g, AttrNamespace(item))
1958 1958 items = sorted(xiter(self.input), key=realkey, reverse=self.reverse)
1959 1959 for item in items:
1960 1960 yield item
1961 1961
1962 1962 def __xrepr__(self, mode="default"):
1963 1963 if mode == "header" or mode == "footer":
1964 1964 input = getattr(self, "input", None)
1965 1965 if input is not None:
1966 1966 for part in xrepr(input, mode):
1967 1967 yield part
1968 1968 yield (astyle.style_default, " | ")
1969 1969 yield (astyle.style_default, "%s(" % self.__class__.__name__)
1970 1970 for part in xrepr(self.key, "default"):
1971 1971 yield part
1972 1972 if self.reverse:
1973 1973 yield (astyle.style_default, ", ")
1974 1974 for part in xrepr(True, "default"):
1975 1975 yield part
1976 1976 yield (astyle.style_default, ")")
1977 1977 else:
1978 1978 yield (astyle.style_default, repr(self))
1979 1979
1980 1980 def __repr__(self):
1981 1981 return "<%s.%s key=%r reverse=%r at 0x%x>" % \
1982 1982 (self.__class__.__module__, self.__class__.__name__,
1983 1983 self.key, self.reverse, id(self))
1984 1984
1985 1985
1986 1986 tab = 3 # for expandtabs()
1987 1987
1988 1988 def _format(field):
1989 1989 if isinstance(field, str):
1990 1990 text = repr(field.expandtabs(tab))[1:-1]
1991 1991 elif isinstance(field, unicode):
1992 1992 text = repr(field.expandtabs(tab))[2:-1]
1993 1993 elif isinstance(field, datetime.datetime):
1994 1994 # Don't use strftime() here, as this requires year >= 1900
1995 1995 text = "%04d-%02d-%02d %02d:%02d:%02d.%06d" % \
1996 1996 (field.year, field.month, field.day,
1997 1997 field.hour, field.minute, field.second, field.microsecond)
1998 1998 elif isinstance(field, datetime.date):
1999 1999 text = "%04d-%02d-%02d" % (field.year, field.month, field.day)
2000 2000 else:
2001 2001 text = repr(field)
2002 2002 return text
2003 2003
2004 2004
2005 2005 class Display(object):
2006 2006 class __metaclass__(type):
2007 2007 def __ror__(self, input):
2008 2008 return input | self()
2009 2009
2010 2010 def __init__(self, input=None):
2011 2011 self.input = input
2012 2012
2013 2013 def __ror__(self, input):
2014 2014 self.input = input
2015 2015 return self
2016 2016
2017 2017 def display(self):
2018 2018 pass
2019 2019
2020 2020
2021 2021 class iless(Display):
2022 2022 cmd = "less --quit-if-one-screen --LONG-PROMPT --LINE-NUMBERS --chop-long-lines --shift=8 --RAW-CONTROL-CHARS"
2023 2023
2024 2024 def display(self):
2025 2025 try:
2026 2026 pager = os.popen(self.cmd, "w")
2027 2027 try:
2028 2028 for item in xiter(self.input):
2029 2029 first = False
2030 2030 for attr in xattrs(item, "default"):
2031 2031 if first:
2032 2032 first = False
2033 2033 else:
2034 2034 pager.write(" ")
2035 2035 attr = upgradexattr(attr)
2036 2036 if not isinstance(attr, SelfDescriptor):
2037 2037 pager.write(attr.name())
2038 2038 pager.write("=")
2039 2039 pager.write(str(attr.value(item)))
2040 2040 pager.write("\n")
2041 2041 finally:
2042 2042 pager.close()
2043 2043 except Exception, exc:
2044 2044 print "%s: %s" % (exc.__class__.__name__, str(exc))
2045 2045
2046 2046
2047 2047 class _RedirectIO(object):
2048 2048 def __init__(self,*args,**kwargs):
2049 2049 """
2050 2050 Map the system output streams to self.
2051 2051 """
2052 2052 self.stream = StringIO.StringIO()
2053 2053 self.stdout = sys.stdout
2054 2054 sys.stdout = self
2055 2055 self.stderr = sys.stderr
2056 2056 sys.stderr = self
2057 2057
2058 2058 def write(self, text):
2059 2059 """
2060 2060 Write both to screen and to self.
2061 2061 """
2062 2062 self.stream.write(text)
2063 2063 self.stdout.write(text)
2064 2064 if "\n" in text:
2065 2065 self.stdout.flush()
2066 2066
2067 2067 def writelines(self, lines):
2068 2068 """
2069 2069 Write lines both to screen and to self.
2070 2070 """
2071 2071 self.stream.writelines(lines)
2072 2072 self.stdout.writelines(lines)
2073 2073 self.stdout.flush()
2074 2074
2075 2075 def restore(self):
2076 2076 """
2077 2077 Restore the default system streams.
2078 2078 """
2079 2079 self.stdout.flush()
2080 2080 self.stderr.flush()
2081 2081 sys.stdout = self.stdout
2082 2082 sys.stderr = self.stderr
2083 2083
2084 2084
2085 2085 class icap(Table):
2086 2086 """
2087 2087 Execute a python string and capture any output to stderr/stdout.
2088 2088
2089 2089 Examples::
2090 2090
2091 2091 >>> import time
2092 2092 >>> icap("for i in range(10): print i, time.sleep(0.1)")
2093 2093
2094 2094 """
2095 2095 skip_doctest = True
2096 2096
2097 2097 def __init__(self, expr, globals=None):
2098 2098 self.expr = expr
2099 2099 self.globals = globals
2100 2100 log = _RedirectIO()
2101 2101 try:
2102 2102 exec(expr, getglobals(globals))
2103 2103 finally:
2104 2104 log.restore()
2105 2105 self.stream = log.stream
2106 2106
2107 2107 def __iter__(self):
2108 2108 self.stream.seek(0)
2109 2109 for line in self.stream:
2110 2110 yield line.rstrip("\r\n")
2111 2111
2112 2112 def __xrepr__(self, mode="default"):
2113 2113 if mode == "header" or mode == "footer":
2114 2114 yield (astyle.style_default,
2115 2115 "%s(%r)" % (self.__class__.__name__, self.expr))
2116 2116 else:
2117 2117 yield (astyle.style_default, repr(self))
2118 2118
2119 2119 def __repr__(self):
2120 2120 return "%s.%s(%r)" % \
2121 2121 (self.__class__.__module__, self.__class__.__name__, self.expr)
2122 2122
2123 2123
2124 2124 def xformat(value, mode, maxlength):
2125 2125 align = None
2126 2126 full = True
2127 2127 width = 0
2128 2128 text = astyle.Text()
2129 2129 for (style, part) in xrepr(value, mode):
2130 2130 # only consider the first result
2131 2131 if align is None:
2132 2132 if isinstance(style, int):
2133 2133 # (style, text) really is (alignment, stop)
2134 2134 align = style
2135 2135 full = part
2136 2136 continue
2137 2137 else:
2138 2138 align = -1
2139 2139 full = True
2140 2140 if not isinstance(style, int):
2141 2141 text.append((style, part))
2142 2142 width += len(part)
2143 2143 if width >= maxlength and not full:
2144 2144 text.append((astyle.style_ellisis, "..."))
2145 2145 width += 3
2146 2146 break
2147 2147 if align is None: # default to left alignment
2148 2148 align = -1
2149 2149 return (align, width, text)
2150 2150
2151 2151
2152 2152
2153 2153 import astyle
2154 2154
2155 2155 class idump(Display):
2156 2156 # The approximate maximum length of a column entry
2157 2157 maxattrlength = 200
2158 2158
2159 2159 # Style for column names
2160 2160 style_header = astyle.Style.fromstr("white:black:bold")
2161 2161
2162 2162 def __init__(self, input=None, *attrs):
2163 2163 Display.__init__(self, input)
2164 2164 self.attrs = [upgradexattr(attr) for attr in attrs]
2165 2165 self.headerpadchar = " "
2166 2166 self.headersepchar = "|"
2167 2167 self.datapadchar = " "
2168 2168 self.datasepchar = "|"
2169 2169
2170 2170 def display(self):
2171 2171 stream = Term.cout
2172 2172 allattrs = []
2173 2173 attrset = set()
2174 2174 colwidths = {}
2175 2175 rows = []
2176 2176 for item in xiter(self.input):
2177 2177 row = {}
2178 2178 attrs = self.attrs
2179 2179 if not attrs:
2180 2180 attrs = xattrs(item, "default")
2181 2181 for attr in attrs:
2182 2182 if attr not in attrset:
2183 2183 allattrs.append(attr)
2184 2184 attrset.add(attr)
2185 2185 colwidths[attr] = len(attr.name())
2186 2186 try:
2187 2187 value = attr.value(item)
2188 2188 except (KeyboardInterrupt, SystemExit):
2189 2189 raise
2190 2190 except Exception, exc:
2191 2191 value = exc
2192 2192 (align, width, text) = xformat(value, "cell", self.maxattrlength)
2193 2193 colwidths[attr] = max(colwidths[attr], width)
2194 2194 # remember alignment, length and colored parts
2195 2195 row[attr] = (align, width, text)
2196 2196 rows.append(row)
2197 2197
2198 2198 stream.write("\n")
2199 2199 for (i, attr) in enumerate(allattrs):
2200 2200 attrname = attr.name()
2201 2201 self.style_header(attrname).write(stream)
2202 2202 spc = colwidths[attr] - len(attrname)
2203 2203 if i < len(colwidths)-1:
2204 2204 stream.write(self.headerpadchar*spc)
2205 2205 stream.write(self.headersepchar)
2206 2206 stream.write("\n")
2207 2207
2208 2208 for row in rows:
2209 2209 for (i, attr) in enumerate(allattrs):
2210 2210 (align, width, text) = row[attr]
2211 2211 spc = colwidths[attr] - width
2212 2212 if align == -1:
2213 2213 text.write(stream)
2214 2214 if i < len(colwidths)-1:
2215 2215 stream.write(self.datapadchar*spc)
2216 2216 elif align == 0:
2217 2217 spc = colwidths[attr] - width
2218 2218 spc1 = spc//2
2219 2219 spc2 = spc-spc1
2220 2220 stream.write(self.datapadchar*spc1)
2221 2221 text.write(stream)
2222 2222 if i < len(colwidths)-1:
2223 2223 stream.write(self.datapadchar*spc2)
2224 2224 else:
2225 2225 stream.write(self.datapadchar*spc)
2226 2226 text.write(stream)
2227 2227 if i < len(colwidths)-1:
2228 2228 stream.write(self.datasepchar)
2229 2229 stream.write("\n")
2230 2230
2231 2231
2232 2232 class AttributeDetail(Table):
2233 2233 """
2234 2234 ``AttributeDetail`` objects are use for displaying a detailed list of object
2235 2235 attributes.
2236 2236 """
2237 2237 def __init__(self, object, descriptor):
2238 2238 self.object = object
2239 2239 self.descriptor = descriptor
2240 2240
2241 2241 def __iter__(self):
2242 2242 return self.descriptor.iter(self.object)
2243 2243
2244 2244 def name(self):
2245 2245 return self.descriptor.name()
2246 2246
2247 2247 def attrtype(self):
2248 2248 return self.descriptor.attrtype(self.object)
2249 2249
2250 2250 def valuetype(self):
2251 2251 return self.descriptor.valuetype(self.object)
2252 2252
2253 2253 def doc(self):
2254 2254 return self.descriptor.doc(self.object)
2255 2255
2256 2256 def shortdoc(self):
2257 2257 return self.descriptor.shortdoc(self.object)
2258 2258
2259 2259 def value(self):
2260 2260 return self.descriptor.value(self.object)
2261 2261
2262 2262 def __xattrs__(self, mode="default"):
2263 2263 attrs = ("name()", "attrtype()", "valuetype()", "value()", "shortdoc()")
2264 2264 if mode == "detail":
2265 2265 attrs += ("doc()",)
2266 2266 return attrs
2267 2267
2268 2268 def __xrepr__(self, mode="default"):
2269 2269 yield (-1, True)
2270 2270 valuetype = self.valuetype()
2271 2271 if valuetype is not noitem:
2272 2272 for part in xrepr(valuetype):
2273 2273 yield part
2274 2274 yield (astyle.style_default, " ")
2275 2275 yield (astyle.style_default, self.attrtype())
2276 2276 yield (astyle.style_default, " ")
2277 2277 yield (astyle.style_default, self.name())
2278 2278 yield (astyle.style_default, " of ")
2279 2279 for part in xrepr(self.object):
2280 2280 yield part
2281 2281
2282 2282
2283 2283 try:
2284 2284 from ibrowse import ibrowse
2285 2285 except ImportError:
2286 2286 # No curses (probably Windows) => try igrid
2287 2287 try:
2288 2288 from igrid import igrid
2289 2289 except ImportError:
2290 2290 # no wx either => use ``idump`` as the default display.
2291 2291 defaultdisplay = idump
2292 2292 else:
2293 2293 defaultdisplay = igrid
2294 2294 __all__.append("igrid")
2295 2295 else:
2296 2296 defaultdisplay = ibrowse
2297 2297 __all__.append("ibrowse")
2298 2298
2299 2299
2300 2300 # If we're running under IPython, register our objects with IPython's
2301 2301 # generic function ``result_display``, else install a displayhook
2302 2302 # directly as sys.displayhook
2303 2303 if generics is not None:
2304 2304 def display_display(obj):
2305 2305 return obj.display()
2306 2306 generics.result_display.when_type(Display)(display_display)
2307 2307
2308 2308 def display_tableobject(obj):
2309 2309 return display_display(defaultdisplay(obj))
2310 2310 generics.result_display.when_type(Table)(display_tableobject)
2311 2311
2312 2312 def display_tableclass(obj):
2313 2313 return display_tableobject(obj())
2314 2314 generics.result_display.when_type(Table.__metaclass__)(display_tableclass)
2315 2315 else:
2316 2316 def installdisplayhook():
2317 2317 _originalhook = sys.displayhook
2318 2318 def displayhook(obj):
2319 2319 if isinstance(obj, type) and issubclass(obj, Table):
2320 2320 obj = obj()
2321 2321 if isinstance(obj, Table):
2322 2322 obj = defaultdisplay(obj)
2323 2323 if isinstance(obj, Display):
2324 2324 return obj.display()
2325 2325 else:
2326 2326 _originalhook(obj)
2327 2327 sys.displayhook = displayhook
2328 2328 installdisplayhook()
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
General Comments 0
You need to be logged in to leave comments. Login now