##// END OF EJS Templates
- thread-safety fixes...
fperez -
Show More

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

@@ -0,0 +1,23 b''
1 """Support for interactive macros in IPython"""
2
3 #*****************************************************************************
4 # Copyright (C) 2001-2005 Fernando Perez <fperez@colorado.edu>
5 #
6 # Distributed under the terms of the BSD License. The full license is in
7 # the file COPYING, distributed as part of this software.
8 #*****************************************************************************
9
10 class Macro:
11 """Simple class to store the value of macros as strings.
12
13 This allows us to later exec them by checking when something is an
14 instance of this class."""
15
16 def __init__(self,data):
17
18 # store the macro value, as a single string which can be evaluated by
19 # runlines()
20 self.value = ''.join(data).rstrip()+'\n'
21
22 def __str__(self):
23 return self.value
@@ -1,2676 +1,2672 b''
1 1 # -*- coding: utf-8 -*-
2 2 """Magic functions for InteractiveShell.
3 3
4 $Id: Magic.py 974 2005-12-29 19:48:33Z fperez $"""
4 $Id: Magic.py 975 2005-12-29 23:50:22Z fperez $"""
5 5
6 6 #*****************************************************************************
7 7 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
8 8 # Copyright (C) 2001-2004 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 # Modules and globals
16 16
17 17 from IPython import Release
18 18 __author__ = '%s <%s>\n%s <%s>' % \
19 19 ( Release.authors['Janko'] + Release.authors['Fernando'] )
20 20 __license__ = Release.license
21 21
22 22 # Python standard modules
23 23 import __builtin__
24 24 import bdb
25 25 import inspect
26 26 import os
27 27 import pdb
28 28 import pydoc
29 29 import sys
30 30 import re
31 31 import tempfile
32 32 import time
33 33 import cPickle as pickle
34 34 from cStringIO import StringIO
35 35 from getopt import getopt
36 36 from pprint import pprint, pformat
37 37
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 # Homebrewed
45 45 from IPython import Debugger, OInspect, wildcard
46 46 from IPython.FakeModule import FakeModule
47 47 from IPython.Itpl import Itpl, itpl, printpl,itplns
48 48 from IPython.PyColorize import Parser
49 49 from IPython.Struct import Struct
50 from IPython.macro import Macro
50 51 from IPython.genutils import *
51 52
52 53 #***************************************************************************
53 54 # Utility functions
54 55 def on_off(tag):
55 56 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
56 57 return ['OFF','ON'][tag]
57 58
58 59
59 #****************************************************************************
60 # Utility classes
61 class Macro(list):
62 """Simple class to store the value of macros as strings.
63
64 This allows us to later exec them by checking when something is an
65 instance of this class."""
66
67 def __init__(self,data):
68 list.__init__(self,data)
69 self.value = ''.join(data)
70
71 60 #***************************************************************************
72 61 # Main class implementing Magic functionality
73 62 class Magic:
74 63 """Magic functions for InteractiveShell.
75 64
76 65 Shell functions which can be reached as %function_name. All magic
77 66 functions should accept a string, which they can parse for their own
78 67 needs. This can make some functions easier to type, eg `%cd ../`
79 68 vs. `%cd("../")`
80 69
81 70 ALL definitions MUST begin with the prefix magic_. The user won't need it
82 71 at the command line, but it is is needed in the definition. """
83 72
84 73 # class globals
85 74 auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.',
86 75 'Automagic is ON, % prefix NOT needed for magic functions.']
87 76
88 77 #......................................................................
89 78 # some utility functions
90 79
91 80 def __init__(self,shell):
92 81
93 82 self.options_table = {}
94 83 if profile is None:
95 84 self.magic_prun = self.profile_missing_notice
96 85 self.shell = shell
97 86
98 87 def profile_missing_notice(self, *args, **kwargs):
99 88 error("""\
100 89 The profile module could not be found. If you are a Debian user,
101 90 it has been removed from the standard Debian package because of its non-free
102 91 license. To use profiling, please install"python2.3-profiler" from non-free.""")
103 92
104 93 def default_option(self,fn,optstr):
105 94 """Make an entry in the options_table for fn, with value optstr"""
106 95
107 96 if fn not in self.lsmagic():
108 97 error("%s is not a magic function" % fn)
109 98 self.options_table[fn] = optstr
110 99
111 100 def lsmagic(self):
112 101 """Return a list of currently available magic functions.
113 102
114 103 Gives a list of the bare names after mangling (['ls','cd', ...], not
115 104 ['magic_ls','magic_cd',...]"""
116 105
117 106 # FIXME. This needs a cleanup, in the way the magics list is built.
118 107
119 108 # magics in class definition
120 109 class_magic = lambda fn: fn.startswith('magic_') and \
121 110 callable(Magic.__dict__[fn])
122 111 # in instance namespace (run-time user additions)
123 112 inst_magic = lambda fn: fn.startswith('magic_') and \
124 113 callable(self.__dict__[fn])
125 114 # and bound magics by user (so they can access self):
126 115 inst_bound_magic = lambda fn: fn.startswith('magic_') and \
127 116 callable(self.__class__.__dict__[fn])
128 117 magics = filter(class_magic,Magic.__dict__.keys()) + \
129 118 filter(inst_magic,self.__dict__.keys()) + \
130 119 filter(inst_bound_magic,self.__class__.__dict__.keys())
131 120 out = []
132 121 for fn in magics:
133 122 out.append(fn.replace('magic_','',1))
134 123 out.sort()
135 124 return out
136 125
137 126 def extract_input_slices(self,slices):
138 127 """Return as a string a set of input history slices.
139 128
140 129 The set of slices is given as a list of strings (like ['1','4:8','9'],
141 130 since this function is for use by magic functions which get their
142 131 arguments as strings."""
143 132
144 133 cmds = []
145 134 for chunk in slices:
146 135 if ':' in chunk:
147 136 ini,fin = map(int,chunk.split(':'))
148 137 else:
149 138 ini = int(chunk)
150 139 fin = ini+1
151 140 cmds.append(self.shell.input_hist[ini:fin])
152 141 return cmds
153 142
154 143 def _ofind(self,oname):
155 144 """Find an object in the available namespaces.
156 145
157 146 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
158 147
159 148 Has special code to detect magic functions.
160 149 """
161 150
162 151 oname = oname.strip()
163 152
164 153 # Namespaces to search in:
165 154 user_ns = self.shell.user_ns
166 155 internal_ns = self.shell.internal_ns
167 156 builtin_ns = __builtin__.__dict__
168 157 alias_ns = self.shell.alias_table
169 158
170 159 # Put them in a list. The order is important so that we find things in
171 160 # the same order that Python finds them.
172 161 namespaces = [ ('Interactive',user_ns),
173 162 ('IPython internal',internal_ns),
174 163 ('Python builtin',builtin_ns),
175 164 ('Alias',alias_ns),
176 165 ]
177 166
178 167 # initialize results to 'null'
179 168 found = 0; obj = None; ospace = None; ds = None;
180 169 ismagic = 0; isalias = 0
181 170
182 171 # Look for the given name by splitting it in parts. If the head is
183 172 # found, then we look for all the remaining parts as members, and only
184 173 # declare success if we can find them all.
185 174 oname_parts = oname.split('.')
186 175 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
187 176 for nsname,ns in namespaces:
188 177 try:
189 178 obj = ns[oname_head]
190 179 except KeyError:
191 180 continue
192 181 else:
193 182 for part in oname_rest:
194 183 try:
195 184 obj = getattr(obj,part)
196 185 except:
197 186 # Blanket except b/c some badly implemented objects
198 187 # allow __getattr__ to raise exceptions other than
199 188 # AttributeError, which then crashes IPython.
200 189 break
201 190 else:
202 191 # If we finish the for loop (no break), we got all members
203 192 found = 1
204 193 ospace = nsname
205 194 if ns == alias_ns:
206 195 isalias = 1
207 196 break # namespace loop
208 197
209 198 # Try to see if it's magic
210 199 if not found:
211 200 if oname.startswith(self.shell.ESC_MAGIC):
212 201 oname = oname[1:]
213 202 obj = getattr(self,'magic_'+oname,None)
214 203 if obj is not None:
215 204 found = 1
216 205 ospace = 'IPython internal'
217 206 ismagic = 1
218 207
219 208 # Last try: special-case some literals like '', [], {}, etc:
220 209 if not found and oname_head in ["''",'""','[]','{}','()']:
221 210 obj = eval(oname_head)
222 211 found = 1
223 212 ospace = 'Interactive'
224 213
225 214 return {'found':found, 'obj':obj, 'namespace':ospace,
226 215 'ismagic':ismagic, 'isalias':isalias}
227 216
228 217 def arg_err(self,func):
229 218 """Print docstring if incorrect arguments were passed"""
230 219 print 'Error in arguments:'
231 220 print OInspect.getdoc(func)
232 221
233
234 222 def format_latex(self,strng):
235 223 """Format a string for latex inclusion."""
236 224
237 225 # Characters that need to be escaped for latex:
238 226 escape_re = re.compile(r'(%|_|\$|#)',re.MULTILINE)
239 227 # Magic command names as headers:
240 228 cmd_name_re = re.compile(r'^(%s.*?):' % self.shell.ESC_MAGIC,
241 229 re.MULTILINE)
242 230 # Magic commands
243 231 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % self.shell.ESC_MAGIC,
244 232 re.MULTILINE)
245 233 # Paragraph continue
246 234 par_re = re.compile(r'\\$',re.MULTILINE)
247 235
248 236 # The "\n" symbol
249 237 newline_re = re.compile(r'\\n')
250 238
251 239 # Now build the string for output:
252 240 strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
253 241 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
254 242 strng = par_re.sub(r'\\\\',strng)
255 243 strng = escape_re.sub(r'\\\1',strng)
256 244 strng = newline_re.sub(r'\\textbackslash{}n',strng)
257 245 return strng
258 246
259 247 def format_screen(self,strng):
260 248 """Format a string for screen printing.
261 249
262 250 This removes some latex-type format codes."""
263 251 # Paragraph continue
264 252 par_re = re.compile(r'\\$',re.MULTILINE)
265 253 strng = par_re.sub('',strng)
266 254 return strng
267 255
268 256 def parse_options(self,arg_str,opt_str,*long_opts,**kw):
269 257 """Parse options passed to an argument string.
270 258
271 259 The interface is similar to that of getopt(), but it returns back a
272 260 Struct with the options as keys and the stripped argument string still
273 261 as a string.
274 262
275 263 arg_str is quoted as a true sys.argv vector by using shlex.split.
276 264 This allows us to easily expand variables, glob files, quote
277 265 arguments, etc.
278 266
279 267 Options:
280 268 -mode: default 'string'. If given as 'list', the argument string is
281 269 returned as a list (split on whitespace) instead of a string.
282 270
283 271 -list_all: put all option values in lists. Normally only options
284 272 appearing more than once are put in a list."""
285 273
286 274 # inject default options at the beginning of the input line
287 275 caller = sys._getframe(1).f_code.co_name.replace('magic_','')
288 276 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
289 277
290 278 mode = kw.get('mode','string')
291 279 if mode not in ['string','list']:
292 280 raise ValueError,'incorrect mode given: %s' % mode
293 281 # Get options
294 282 list_all = kw.get('list_all',0)
295 283
296 284 # Check if we have more than one argument to warrant extra processing:
297 285 odict = {} # Dictionary with options
298 286 args = arg_str.split()
299 287 if len(args) >= 1:
300 288 # If the list of inputs only has 0 or 1 thing in it, there's no
301 289 # need to look for options
302 290 argv = shlex_split(arg_str)
303 291 # Do regular option processing
304 292 opts,args = getopt(argv,opt_str,*long_opts)
305 293 for o,a in opts:
306 294 if o.startswith('--'):
307 295 o = o[2:]
308 296 else:
309 297 o = o[1:]
310 298 try:
311 299 odict[o].append(a)
312 300 except AttributeError:
313 301 odict[o] = [odict[o],a]
314 302 except KeyError:
315 303 if list_all:
316 304 odict[o] = [a]
317 305 else:
318 306 odict[o] = a
319 307
320 308 # Prepare opts,args for return
321 309 opts = Struct(odict)
322 310 if mode == 'string':
323 311 args = ' '.join(args)
324 312
325 313 return opts,args
326 314
327 315 #......................................................................
328 316 # And now the actual magic functions
329 317
330 318 # Functions for IPython shell work (vars,funcs, config, etc)
331 319 def magic_lsmagic(self, parameter_s = ''):
332 320 """List currently available magic functions."""
333 321 mesc = self.shell.ESC_MAGIC
334 322 print 'Available magic functions:\n'+mesc+\
335 323 (' '+mesc).join(self.lsmagic())
336 324 print '\n' + Magic.auto_status[self.shell.rc.automagic]
337 325 return None
338 326
339 327 def magic_magic(self, parameter_s = ''):
340 328 """Print information about the magic function system."""
341 329
342 330 mode = ''
343 331 try:
344 332 if parameter_s.split()[0] == '-latex':
345 333 mode = 'latex'
346 334 except:
347 335 pass
348 336
349 337 magic_docs = []
350 338 for fname in self.lsmagic():
351 339 mname = 'magic_' + fname
352 340 for space in (Magic,self,self.__class__):
353 341 try:
354 342 fn = space.__dict__[mname]
355 343 except KeyError:
356 344 pass
357 345 else:
358 346 break
359 347 magic_docs.append('%s%s:\n\t%s\n' %(self.shell.ESC_MAGIC,
360 348 fname,fn.__doc__))
361 349 magic_docs = ''.join(magic_docs)
362 350
363 351 if mode == 'latex':
364 352 print self.format_latex(magic_docs)
365 353 return
366 354 else:
367 355 magic_docs = self.format_screen(magic_docs)
368 356
369 357 outmsg = """
370 358 IPython's 'magic' functions
371 359 ===========================
372 360
373 361 The magic function system provides a series of functions which allow you to
374 362 control the behavior of IPython itself, plus a lot of system-type
375 363 features. All these functions are prefixed with a % character, but parameters
376 364 are given without parentheses or quotes.
377 365
378 366 NOTE: If you have 'automagic' enabled (via the command line option or with the
379 367 %automagic function), you don't need to type in the % explicitly. By default,
380 368 IPython ships with automagic on, so you should only rarely need the % escape.
381 369
382 370 Example: typing '%cd mydir' (without the quotes) changes you working directory
383 371 to 'mydir', if it exists.
384 372
385 373 You can define your own magic functions to extend the system. See the supplied
386 374 ipythonrc and example-magic.py files for details (in your ipython
387 375 configuration directory, typically $HOME/.ipython/).
388 376
389 377 You can also define your own aliased names for magic functions. In your
390 378 ipythonrc file, placing a line like:
391 379
392 380 execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
393 381
394 382 will define %pf as a new name for %profile.
395 383
396 384 You can also call magics in code using the ipmagic() function, which IPython
397 385 automatically adds to the builtin namespace. Type 'ipmagic?' for details.
398 386
399 387 For a list of the available magic functions, use %lsmagic. For a description
400 388 of any of them, type %magic_name?, e.g. '%cd?'.
401 389
402 390 Currently the magic system has the following functions:\n"""
403 391
404 392 mesc = self.shell.ESC_MAGIC
405 393 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
406 394 "\n\n%s%s\n\n%s" % (outmsg,
407 395 magic_docs,mesc,mesc,
408 396 (' '+mesc).join(self.lsmagic()),
409 397 Magic.auto_status[self.shell.rc.automagic] ) )
410 398
411 399 page(outmsg,screen_lines=self.shell.rc.screen_length)
412 400
413 401 def magic_automagic(self, parameter_s = ''):
414 402 """Make magic functions callable without having to type the initial %.
415 403
416 404 Toggles on/off (when off, you must call it as %automagic, of
417 405 course). Note that magic functions have lowest priority, so if there's
418 406 a variable whose name collides with that of a magic fn, automagic
419 407 won't work for that function (you get the variable instead). However,
420 408 if you delete the variable (del var), the previously shadowed magic
421 409 function becomes visible to automagic again."""
422 410
423 411 rc = self.shell.rc
424 412 rc.automagic = not rc.automagic
425 413 print '\n' + Magic.auto_status[rc.automagic]
426 414
427 415 def magic_autocall(self, parameter_s = ''):
428 416 """Make functions callable without having to type parentheses.
429 417
430 418 This toggles the autocall command line option on and off."""
431 419
432 420 rc = self.shell.rc
433 421 rc.autocall = not rc.autocall
434 422 print "Automatic calling is:",['OFF','ON'][rc.autocall]
435 423
436 424 def magic_autoindent(self, parameter_s = ''):
437 425 """Toggle autoindent on/off (if available)."""
438 426
439 427 self.shell.set_autoindent()
440 428 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
441 429
442 430 def magic_system_verbose(self, parameter_s = ''):
443 431 """Toggle verbose printing of system calls on/off."""
444 432
445 433 self.shell.rc_set_toggle('system_verbose')
446 434 print "System verbose printing is:",\
447 435 ['OFF','ON'][self.shell.rc.system_verbose]
448 436
449 437 def magic_history(self, parameter_s = ''):
450 438 """Print input history (_i<n> variables), with most recent last.
451 439
452 440 %history [-n] -> print at most 40 inputs (some may be multi-line)\\
453 441 %history [-n] n -> print at most n inputs\\
454 442 %history [-n] n1 n2 -> print inputs between n1 and n2 (n2 not included)\\
455 443
456 444 Each input's number <n> is shown, and is accessible as the
457 445 automatically generated variable _i<n>. Multi-line statements are
458 446 printed starting at a new line for easy copy/paste.
459 447
460 448 If option -n is used, input numbers are not printed. This is useful if
461 449 you want to get a printout of many lines which can be directly pasted
462 450 into a text editor.
463 451
464 452 This feature is only available if numbered prompts are in use."""
465 453
466 454 if not self.shell.outputcache.do_full_cache:
467 455 print 'This feature is only available if numbered prompts are in use.'
468 456 return
469 457 opts,args = self.parse_options(parameter_s,'n',mode='list')
470 458
471 459 default_length = 40
472 460 if len(args) == 0:
473 461 final = self.shell.outputcache.prompt_count
474 462 init = max(1,final-default_length)
475 463 elif len(args) == 1:
476 464 final = self.shell.outputcache.prompt_count
477 465 init = max(1,final-int(args[0]))
478 466 elif len(args) == 2:
479 467 init,final = map(int,args)
480 468 else:
481 469 warn('%hist takes 0, 1 or 2 arguments separated by spaces.')
482 470 print self.magic_hist.__doc__
483 471 return
484 472 width = len(str(final))
485 473 line_sep = ['','\n']
486 474 input_hist = self.shell.input_hist
487 475 print_nums = not opts.has_key('n')
488 476 for in_num in range(init,final):
489 477 inline = input_hist[in_num]
490 478 multiline = inline.count('\n') > 1
491 479 if print_nums:
492 480 print str(in_num).ljust(width)+':'+ line_sep[multiline],
493 481 if inline.startswith('#'+self.shell.ESC_MAGIC) or \
494 482 inline.startswith('#!'):
495 483 print inline[1:],
496 484 else:
497 485 print inline,
498 486
499 487 def magic_hist(self, parameter_s=''):
500 488 """Alternate name for %history."""
501 489 return self.magic_history(parameter_s)
502 490
503 491 def magic_p(self, parameter_s=''):
504 492 """Just a short alias for Python's 'print'."""
505 493 exec 'print ' + parameter_s in self.shell.user_ns
506 494
507 495 def magic_r(self, parameter_s=''):
508 496 """Repeat previous input.
509 497
510 498 If given an argument, repeats the previous command which starts with
511 499 the same string, otherwise it just repeats the previous input.
512 500
513 501 Shell escaped commands (with ! as first character) are not recognized
514 502 by this system, only pure python code and magic commands.
515 503 """
516 504
517 505 start = parameter_s.strip()
518 506 esc_magic = self.shell.ESC_MAGIC
519 507 # Identify magic commands even if automagic is on (which means
520 508 # the in-memory version is different from that typed by the user).
521 509 if self.shell.rc.automagic:
522 510 start_magic = esc_magic+start
523 511 else:
524 512 start_magic = start
525 513 # Look through the input history in reverse
526 514 for n in range(len(self.shell.input_hist)-2,0,-1):
527 515 input = self.shell.input_hist[n]
528 516 # skip plain 'r' lines so we don't recurse to infinity
529 517 if input != 'ipmagic("r")\n' and \
530 518 (input.startswith(start) or input.startswith(start_magic)):
531 519 #print 'match',`input` # dbg
532 520 print 'Executing:',input,
533 521 self.shell.runlines(input)
534 522 return
535 523 print 'No previous input matching `%s` found.' % start
536 524
537 525 def magic_page(self, parameter_s=''):
538 526 """Pretty print the object and display it through a pager.
539 527
540 528 If no parameter is given, use _ (last output)."""
541 529 # After a function contributed by Olivier Aubert, slightly modified.
542 530
543 531 oname = parameter_s and parameter_s or '_'
544 532 info = self._ofind(oname)
545 533 if info['found']:
546 534 page(pformat(info['obj']))
547 535 else:
548 536 print 'Object `%s` not found' % oname
549 537
550 538 def magic_profile(self, parameter_s=''):
551 539 """Print your currently active IPyhton profile."""
552 540 if self.shell.rc.profile:
553 541 printpl('Current IPython profile: $self.shell.rc.profile.')
554 542 else:
555 543 print 'No profile active.'
556 544
557 545 def _inspect(self,meth,oname,**kw):
558 546 """Generic interface to the inspector system.
559 547
560 548 This function is meant to be called by pdef, pdoc & friends."""
561 549
562 550 oname = oname.strip()
563 551 info = Struct(self._ofind(oname))
564 552 if info.found:
565 553 pmethod = getattr(self.shell.inspector,meth)
566 554 formatter = info.ismagic and self.format_screen or None
567 555 if meth == 'pdoc':
568 556 pmethod(info.obj,oname,formatter)
569 557 elif meth == 'pinfo':
570 558 pmethod(info.obj,oname,formatter,info,**kw)
571 559 else:
572 560 pmethod(info.obj,oname)
573 561 else:
574 562 print 'Object `%s` not found.' % oname
575 563 return 'not found' # so callers can take other action
576 564
577 565 def magic_pdef(self, parameter_s=''):
578 566 """Print the definition header for any callable object.
579 567
580 568 If the object is a class, print the constructor information."""
581 569 self._inspect('pdef',parameter_s)
582 570
583 571 def magic_pdoc(self, parameter_s=''):
584 572 """Print the docstring for an object.
585 573
586 574 If the given object is a class, it will print both the class and the
587 575 constructor docstrings."""
588 576 self._inspect('pdoc',parameter_s)
589 577
590 578 def magic_psource(self, parameter_s=''):
591 579 """Print (or run through pager) the source code for an object."""
592 580 self._inspect('psource',parameter_s)
593 581
594 582 def magic_pfile(self, parameter_s=''):
595 583 """Print (or run through pager) the file where an object is defined.
596 584
597 585 The file opens at the line where the object definition begins. IPython
598 586 will honor the environment variable PAGER if set, and otherwise will
599 587 do its best to print the file in a convenient form.
600 588
601 589 If the given argument is not an object currently defined, IPython will
602 590 try to interpret it as a filename (automatically adding a .py extension
603 591 if needed). You can thus use %pfile as a syntax highlighting code
604 592 viewer."""
605 593
606 594 # first interpret argument as an object name
607 595 out = self._inspect('pfile',parameter_s)
608 596 # if not, try the input as a filename
609 597 if out == 'not found':
610 598 try:
611 599 filename = get_py_filename(parameter_s)
612 600 except IOError,msg:
613 601 print msg
614 602 return
615 603 page(self.shell.inspector.format(file(filename).read()))
616 604
617 605 def magic_pinfo(self, parameter_s=''):
618 606 """Provide detailed information about an object.
619 607
620 608 '%pinfo object' is just a synonym for object? or ?object."""
621 609
622 610 #print 'pinfo par: <%s>' % parameter_s # dbg
623 611
624 612 # detail_level: 0 -> obj? , 1 -> obj??
625 613 detail_level = 0
626 614 # We need to detect if we got called as 'pinfo pinfo foo', which can
627 615 # happen if the user types 'pinfo foo?' at the cmd line.
628 616 pinfo,qmark1,oname,qmark2 = \
629 617 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
630 618 if pinfo or qmark1 or qmark2:
631 619 detail_level = 1
632 620 if "*" in oname:
633 621 self.magic_psearch(oname)
634 622 else:
635 623 self._inspect('pinfo',oname,detail_level=detail_level)
636 624
637 625 def magic_psearch(self, parameter_s=''):
638 626 """Search for object in namespaces by wildcard.
639 627
640 628 %psearch [options] PATTERN [OBJECT TYPE]
641 629
642 630 Note: ? can be used as a synonym for %psearch, at the beginning or at
643 631 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
644 632 rest of the command line must be unchanged (options come first), so
645 633 for example the following forms are equivalent
646 634
647 635 %psearch -i a* function
648 636 -i a* function?
649 637 ?-i a* function
650 638
651 639 Arguments:
652 640
653 641 PATTERN
654 642
655 643 where PATTERN is a string containing * as a wildcard similar to its
656 644 use in a shell. The pattern is matched in all namespaces on the
657 645 search path. By default objects starting with a single _ are not
658 646 matched, many IPython generated objects have a single
659 647 underscore. The default is case insensitive matching. Matching is
660 648 also done on the attributes of objects and not only on the objects
661 649 in a module.
662 650
663 651 [OBJECT TYPE]
664 652
665 653 Is the name of a python type from the types module. The name is
666 654 given in lowercase without the ending type, ex. StringType is
667 655 written string. By adding a type here only objects matching the
668 656 given type are matched. Using all here makes the pattern match all
669 657 types (this is the default).
670 658
671 659 Options:
672 660
673 661 -a: makes the pattern match even objects whose names start with a
674 662 single underscore. These names are normally ommitted from the
675 663 search.
676 664
677 665 -i/-c: make the pattern case insensitive/sensitive. If neither of
678 666 these options is given, the default is read from your ipythonrc
679 667 file. The option name which sets this value is
680 668 'wildcards_case_sensitive'. If this option is not specified in your
681 669 ipythonrc file, IPython's internal default is to do a case sensitive
682 670 search.
683 671
684 672 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
685 673 specifiy can be searched in any of the following namespaces:
686 674 'builtin', 'user', 'user_global','internal', 'alias', where
687 675 'builtin' and 'user' are the search defaults. Note that you should
688 676 not use quotes when specifying namespaces.
689 677
690 678 'Builtin' contains the python module builtin, 'user' contains all
691 679 user data, 'alias' only contain the shell aliases and no python
692 680 objects, 'internal' contains objects used by IPython. The
693 681 'user_global' namespace is only used by embedded IPython instances,
694 682 and it contains module-level globals. You can add namespaces to the
695 683 search with -s or exclude them with -e (these options can be given
696 684 more than once).
697 685
698 686 Examples:
699 687
700 688 %psearch a* -> objects beginning with an a
701 689 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
702 690 %psearch a* function -> all functions beginning with an a
703 691 %psearch re.e* -> objects beginning with an e in module re
704 692 %psearch r*.e* -> objects that start with e in modules starting in r
705 693 %psearch r*.* string -> all strings in modules beginning with r
706 694
707 695 Case sensitve search:
708 696
709 697 %psearch -c a* list all object beginning with lower case a
710 698
711 699 Show objects beginning with a single _:
712 700
713 701 %psearch -a _* list objects beginning with a single underscore"""
714 702
715 703 # default namespaces to be searched
716 704 def_search = ['user','builtin']
717 705
718 706 # Process options/args
719 707 opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
720 708 opt = opts.get
721 709 shell = self.shell
722 710 psearch = shell.inspector.psearch
723 711
724 712 # select case options
725 713 if opts.has_key('i'):
726 714 ignore_case = True
727 715 elif opts.has_key('c'):
728 716 ignore_case = False
729 717 else:
730 718 ignore_case = not shell.rc.wildcards_case_sensitive
731 719
732 720 # Build list of namespaces to search from user options
733 721 def_search.extend(opt('s',[]))
734 722 ns_exclude = ns_exclude=opt('e',[])
735 723 ns_search = [nm for nm in def_search if nm not in ns_exclude]
736 724
737 725 # Call the actual search
738 726 try:
739 727 psearch(args,shell.ns_table,ns_search,
740 728 show_all=opt('a'),ignore_case=ignore_case)
741 729 except:
742 730 shell.showtraceback()
743 731
744 732 def magic_who_ls(self, parameter_s=''):
745 733 """Return a sorted list of all interactive variables.
746 734
747 735 If arguments are given, only variables of types matching these
748 736 arguments are returned."""
749 737
750 738 user_ns = self.shell.user_ns
751 739 out = []
752 740 typelist = parameter_s.split()
753 741 for i in self.shell.user_ns.keys():
754 742 if not (i.startswith('_') or i.startswith('_i')) \
755 743 and not (self.shell.internal_ns.has_key(i) or
756 744 self.shell.user_config_ns.has_key(i)):
757 745 if typelist:
758 746 if type(user_ns[i]).__name__ in typelist:
759 747 out.append(i)
760 748 else:
761 749 out.append(i)
762 750 out.sort()
763 751 return out
764 752
765 753 def magic_who(self, parameter_s=''):
766 754 """Print all interactive variables, with some minimal formatting.
767 755
768 756 If any arguments are given, only variables whose type matches one of
769 757 these are printed. For example:
770 758
771 759 %who function str
772 760
773 761 will only list functions and strings, excluding all other types of
774 762 variables. To find the proper type names, simply use type(var) at a
775 763 command line to see how python prints type names. For example:
776 764
777 765 In [1]: type('hello')\\
778 766 Out[1]: <type 'str'>
779 767
780 768 indicates that the type name for strings is 'str'.
781 769
782 770 %who always excludes executed names loaded through your configuration
783 771 file and things which are internal to IPython.
784 772
785 773 This is deliberate, as typically you may load many modules and the
786 774 purpose of %who is to show you only what you've manually defined."""
787 775
788 776 varlist = self.magic_who_ls(parameter_s)
789 777 if not varlist:
790 778 print 'Interactive namespace is empty.'
791 779 return
792 780
793 781 # if we have variables, move on...
794 782
795 783 # stupid flushing problem: when prompts have no separators, stdout is
796 784 # getting lost. I'm starting to think this is a python bug. I'm having
797 785 # to force a flush with a print because even a sys.stdout.flush
798 786 # doesn't seem to do anything!
799 787
800 788 count = 0
801 789 for i in varlist:
802 790 print i+'\t',
803 791 count += 1
804 792 if count > 8:
805 793 count = 0
806 794 print
807 795 sys.stdout.flush() # FIXME. Why the hell isn't this flushing???
808 796
809 797 print # well, this does force a flush at the expense of an extra \n
810 798
811 799 def magic_whos(self, parameter_s=''):
812 800 """Like %who, but gives some extra information about each variable.
813 801
814 802 The same type filtering of %who can be applied here.
815 803
816 804 For all variables, the type is printed. Additionally it prints:
817 805
818 806 - For {},[],(): their length.
819 807
820 808 - For Numeric arrays, a summary with shape, number of elements,
821 809 typecode and size in memory.
822 810
823 811 - Everything else: a string representation, snipping their middle if
824 812 too long."""
825 813
826 814 varnames = self.magic_who_ls(parameter_s)
827 815 if not varnames:
828 816 print 'Interactive namespace is empty.'
829 817 return
830 818
831 819 # if we have variables, move on...
832 820
833 821 # for these types, show len() instead of data:
834 822 seq_types = [types.DictType,types.ListType,types.TupleType]
835 823
836 824 # for Numeric arrays, display summary info
837 825 try:
838 826 import Numeric
839 827 except ImportError:
840 828 array_type = None
841 829 else:
842 830 array_type = Numeric.ArrayType.__name__
843 831
844 832 # Find all variable names and types so we can figure out column sizes
845 833 get_vars = lambda i: self.shell.user_ns[i]
846 834 type_name = lambda v: type(v).__name__
847 835 varlist = map(get_vars,varnames)
848 typelist = map(type_name,varlist)
836
837 typelist = []
838 for vv in varlist:
839 tt = type_name(vv)
840 if tt=='instance':
841 typelist.append(str(vv.__class__))
842 else:
843 typelist.append(tt)
844
849 845 # column labels and # of spaces as separator
850 846 varlabel = 'Variable'
851 847 typelabel = 'Type'
852 848 datalabel = 'Data/Info'
853 849 colsep = 3
854 850 # variable format strings
855 851 vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)"
856 852 vfmt_short = '$vstr[:25]<...>$vstr[-25:]'
857 853 aformat = "%s: %s elems, type `%s`, %s bytes"
858 854 # find the size of the columns to format the output nicely
859 855 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
860 856 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
861 857 # table header
862 858 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
863 859 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
864 860 # and the table itself
865 861 kb = 1024
866 862 Mb = 1048576 # kb**2
867 863 for vname,var,vtype in zip(varnames,varlist,typelist):
868 864 print itpl(vformat),
869 865 if vtype in seq_types:
870 866 print len(var)
871 867 elif vtype==array_type:
872 868 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
873 869 vsize = Numeric.size(var)
874 870 vbytes = vsize*var.itemsize()
875 871 if vbytes < 100000:
876 872 print aformat % (vshape,vsize,var.typecode(),vbytes)
877 873 else:
878 874 print aformat % (vshape,vsize,var.typecode(),vbytes),
879 875 if vbytes < Mb:
880 876 print '(%s kb)' % (vbytes/kb,)
881 877 else:
882 878 print '(%s Mb)' % (vbytes/Mb,)
883 879 else:
884 vstr = str(var)
880 vstr = str(var).replace('\n','\\n')
885 881 if len(vstr) < 50:
886 882 print vstr
887 883 else:
888 884 printpl(vfmt_short)
889 885
890 886 def magic_reset(self, parameter_s=''):
891 887 """Resets the namespace by removing all names defined by the user.
892 888
893 889 Input/Output history are left around in case you need them."""
894 890
895 891 ans = raw_input(
896 892 "Once deleted, variables cannot be recovered. Proceed (y/n)? ")
897 893 if not ans.lower() == 'y':
898 894 print 'Nothing done.'
899 895 return
900 896 user_ns = self.shell.user_ns
901 897 for i in self.magic_who_ls():
902 898 del(user_ns[i])
903 899
904 900 def magic_config(self,parameter_s=''):
905 901 """Show IPython's internal configuration."""
906 902
907 903 page('Current configuration structure:\n'+
908 904 pformat(self.shell.rc.dict()))
909 905
910 906 def magic_logstart(self,parameter_s=''):
911 907 """Start logging anywhere in a session.
912 908
913 909 %logstart [-o|-t] [log_name [log_mode]]
914 910
915 911 If no name is given, it defaults to a file named 'ipython_log.py' in your
916 912 current directory, in 'rotate' mode (see below).
917 913
918 914 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
919 915 history up to that point and then continues logging.
920 916
921 917 %logstart takes a second optional parameter: logging mode. This can be one
922 918 of (note that the modes are given unquoted):\\
923 919 append: well, that says it.\\
924 920 backup: rename (if exists) to name~ and start name.\\
925 921 global: single logfile in your home dir, appended to.\\
926 922 over : overwrite existing log.\\
927 923 rotate: create rotating logs name.1~, name.2~, etc.
928 924
929 925 Options:
930 926
931 927 -o: log also IPython's output. In this mode, all commands which
932 928 generate an Out[NN] prompt are recorded to the logfile, right after
933 929 their corresponding input line. The output lines are always
934 930 prepended with a '#[Out]# ' marker, so that the log remains valid
935 931 Python code.
936 932
937 933 Since this marker is always the same, filtering only the output from
938 934 a log is very easy, using for example a simple awk call:
939 935
940 936 awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py
941 937
942 938 -t: put timestamps before each input line logged (these are put in
943 939 comments)."""
944 940
945 941 opts,par = self.parse_options(parameter_s,'ot')
946 942 log_output = 'o' in opts
947 943 timestamp = 't' in opts
948 944
949 945 rc = self.shell.rc
950 946 logger = self.shell.logger
951 947
952 948 # if no args are given, the defaults set in the logger constructor by
953 949 # ipytohn remain valid
954 950 if par:
955 951 try:
956 952 logfname,logmode = par.split()
957 953 except:
958 954 logfname = par
959 955 logmode = 'backup'
960 956 else:
961 957 logfname = logger.logfname
962 958 logmode = logger.logmode
963 959 # put logfname into rc struct as if it had been called on the command
964 960 # line, so it ends up saved in the log header Save it in case we need
965 961 # to restore it...
966 962 old_logfile = rc.opts.get('logfile','')
967 963 if logfname:
968 964 logfname = os.path.expanduser(logfname)
969 965 rc.opts.logfile = logfname
970 966 loghead = self.shell.loghead_tpl % (rc.opts,rc.args)
971 967 try:
972 968 started = logger.logstart(logfname,loghead,logmode,
973 969 log_output,timestamp)
974 970 except:
975 971 rc.opts.logfile = old_logfile
976 972 warn("Couldn't start log: %s" % sys.exc_info()[1])
977 973 else:
978 974 # log input history up to this point, optionally interleaving
979 975 # output if requested
980 976
981 977 if timestamp:
982 978 # disable timestamping for the previous history, since we've
983 979 # lost those already (no time machine here).
984 980 logger.timestamp = False
985 981 if log_output:
986 982 log_write = logger.log_write
987 983 input_hist = self.shell.input_hist
988 984 output_hist = self.shell.output_hist
989 985 for n in range(1,len(input_hist)-1):
990 986 log_write(input_hist[n].rstrip())
991 987 if n in output_hist:
992 988 log_write(repr(output_hist[n]),'output')
993 989 else:
994 990 logger.log_write(self.shell.input_hist[1:])
995 991 if timestamp:
996 992 # re-enable timestamping
997 993 logger.timestamp = True
998 994
999 995 print ('Activating auto-logging. '
1000 996 'Current session state plus future input saved.')
1001 997 logger.logstate()
1002 998
1003 999 def magic_logoff(self,parameter_s=''):
1004 1000 """Temporarily stop logging.
1005 1001
1006 1002 You must have previously started logging."""
1007 1003 self.shell.logger.switch_log(0)
1008 1004
1009 1005 def magic_logon(self,parameter_s=''):
1010 1006 """Restart logging.
1011 1007
1012 1008 This function is for restarting logging which you've temporarily
1013 1009 stopped with %logoff. For starting logging for the first time, you
1014 1010 must use the %logstart function, which allows you to specify an
1015 1011 optional log filename."""
1016 1012
1017 1013 self.shell.logger.switch_log(1)
1018 1014
1019 1015 def magic_logstate(self,parameter_s=''):
1020 1016 """Print the status of the logging system."""
1021 1017
1022 1018 self.shell.logger.logstate()
1023 1019
1024 1020 def magic_pdb(self, parameter_s=''):
1025 1021 """Control the calling of the pdb interactive debugger.
1026 1022
1027 1023 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1028 1024 argument it works as a toggle.
1029 1025
1030 1026 When an exception is triggered, IPython can optionally call the
1031 1027 interactive pdb debugger after the traceback printout. %pdb toggles
1032 1028 this feature on and off."""
1033 1029
1034 1030 par = parameter_s.strip().lower()
1035 1031
1036 1032 if par:
1037 1033 try:
1038 1034 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
1039 1035 except KeyError:
1040 1036 print ('Incorrect argument. Use on/1, off/0, '
1041 1037 'or nothing for a toggle.')
1042 1038 return
1043 1039 else:
1044 1040 # toggle
1045 1041 new_pdb = not self.shell.InteractiveTB.call_pdb
1046 1042
1047 1043 # set on the shell
1048 1044 self.shell.call_pdb = new_pdb
1049 1045 print 'Automatic pdb calling has been turned',on_off(new_pdb)
1050 1046
1051 1047 def magic_prun(self, parameter_s ='',user_mode=1,
1052 1048 opts=None,arg_lst=None,prog_ns=None):
1053 1049
1054 1050 """Run a statement through the python code profiler.
1055 1051
1056 1052 Usage:\\
1057 1053 %prun [options] statement
1058 1054
1059 1055 The given statement (which doesn't require quote marks) is run via the
1060 1056 python profiler in a manner similar to the profile.run() function.
1061 1057 Namespaces are internally managed to work correctly; profile.run
1062 1058 cannot be used in IPython because it makes certain assumptions about
1063 1059 namespaces which do not hold under IPython.
1064 1060
1065 1061 Options:
1066 1062
1067 1063 -l <limit>: you can place restrictions on what or how much of the
1068 1064 profile gets printed. The limit value can be:
1069 1065
1070 1066 * A string: only information for function names containing this string
1071 1067 is printed.
1072 1068
1073 1069 * An integer: only these many lines are printed.
1074 1070
1075 1071 * A float (between 0 and 1): this fraction of the report is printed
1076 1072 (for example, use a limit of 0.4 to see the topmost 40% only).
1077 1073
1078 1074 You can combine several limits with repeated use of the option. For
1079 1075 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1080 1076 information about class constructors.
1081 1077
1082 1078 -r: return the pstats.Stats object generated by the profiling. This
1083 1079 object has all the information about the profile in it, and you can
1084 1080 later use it for further analysis or in other functions.
1085 1081
1086 1082 Since magic functions have a particular form of calling which prevents
1087 1083 you from writing something like:\\
1088 1084 In [1]: p = %prun -r print 4 # invalid!\\
1089 1085 you must instead use IPython's automatic variables to assign this:\\
1090 1086 In [1]: %prun -r print 4 \\
1091 1087 Out[1]: <pstats.Stats instance at 0x8222cec>\\
1092 1088 In [2]: stats = _
1093 1089
1094 1090 If you really need to assign this value via an explicit function call,
1095 1091 you can always tap directly into the true name of the magic function
1096 1092 by using the ipmagic function (which IPython automatically adds to the
1097 1093 builtins):\\
1098 1094 In [3]: stats = ipmagic('prun','-r print 4')
1099 1095
1100 1096 You can type ipmagic? for more details on ipmagic.
1101 1097
1102 1098 -s <key>: sort profile by given key. You can provide more than one key
1103 1099 by using the option several times: '-s key1 -s key2 -s key3...'. The
1104 1100 default sorting key is 'time'.
1105 1101
1106 1102 The following is copied verbatim from the profile documentation
1107 1103 referenced below:
1108 1104
1109 1105 When more than one key is provided, additional keys are used as
1110 1106 secondary criteria when the there is equality in all keys selected
1111 1107 before them.
1112 1108
1113 1109 Abbreviations can be used for any key names, as long as the
1114 1110 abbreviation is unambiguous. The following are the keys currently
1115 1111 defined:
1116 1112
1117 1113 Valid Arg Meaning\\
1118 1114 "calls" call count\\
1119 1115 "cumulative" cumulative time\\
1120 1116 "file" file name\\
1121 1117 "module" file name\\
1122 1118 "pcalls" primitive call count\\
1123 1119 "line" line number\\
1124 1120 "name" function name\\
1125 1121 "nfl" name/file/line\\
1126 1122 "stdname" standard name\\
1127 1123 "time" internal time
1128 1124
1129 1125 Note that all sorts on statistics are in descending order (placing
1130 1126 most time consuming items first), where as name, file, and line number
1131 1127 searches are in ascending order (i.e., alphabetical). The subtle
1132 1128 distinction between "nfl" and "stdname" is that the standard name is a
1133 1129 sort of the name as printed, which means that the embedded line
1134 1130 numbers get compared in an odd way. For example, lines 3, 20, and 40
1135 1131 would (if the file names were the same) appear in the string order
1136 1132 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1137 1133 line numbers. In fact, sort_stats("nfl") is the same as
1138 1134 sort_stats("name", "file", "line").
1139 1135
1140 1136 -T <filename>: save profile results as shown on screen to a text
1141 1137 file. The profile is still shown on screen.
1142 1138
1143 1139 -D <filename>: save (via dump_stats) profile statistics to given
1144 1140 filename. This data is in a format understod by the pstats module, and
1145 1141 is generated by a call to the dump_stats() method of profile
1146 1142 objects. The profile is still shown on screen.
1147 1143
1148 1144 If you want to run complete programs under the profiler's control, use
1149 1145 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1150 1146 contains profiler specific options as described here.
1151 1147
1152 1148 You can read the complete documentation for the profile module with:\\
1153 1149 In [1]: import profile; profile.help() """
1154 1150
1155 1151 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1156 1152 # protect user quote marks
1157 1153 parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'")
1158 1154
1159 1155 if user_mode: # regular user call
1160 1156 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:',
1161 1157 list_all=1)
1162 1158 namespace = self.shell.user_ns
1163 1159 else: # called to run a program by %run -p
1164 1160 try:
1165 1161 filename = get_py_filename(arg_lst[0])
1166 1162 except IOError,msg:
1167 1163 error(msg)
1168 1164 return
1169 1165
1170 1166 arg_str = 'execfile(filename,prog_ns)'
1171 1167 namespace = locals()
1172 1168
1173 1169 opts.merge(opts_def)
1174 1170
1175 1171 prof = profile.Profile()
1176 1172 try:
1177 1173 prof = prof.runctx(arg_str,namespace,namespace)
1178 1174 sys_exit = ''
1179 1175 except SystemExit:
1180 1176 sys_exit = """*** SystemExit exception caught in code being profiled."""
1181 1177
1182 1178 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1183 1179
1184 1180 lims = opts.l
1185 1181 if lims:
1186 1182 lims = [] # rebuild lims with ints/floats/strings
1187 1183 for lim in opts.l:
1188 1184 try:
1189 1185 lims.append(int(lim))
1190 1186 except ValueError:
1191 1187 try:
1192 1188 lims.append(float(lim))
1193 1189 except ValueError:
1194 1190 lims.append(lim)
1195 1191
1196 1192 # trap output
1197 1193 sys_stdout = sys.stdout
1198 1194 stdout_trap = StringIO()
1199 1195 try:
1200 1196 sys.stdout = stdout_trap
1201 1197 stats.print_stats(*lims)
1202 1198 finally:
1203 1199 sys.stdout = sys_stdout
1204 1200 output = stdout_trap.getvalue()
1205 1201 output = output.rstrip()
1206 1202
1207 1203 page(output,screen_lines=self.shell.rc.screen_length)
1208 1204 print sys_exit,
1209 1205
1210 1206 dump_file = opts.D[0]
1211 1207 text_file = opts.T[0]
1212 1208 if dump_file:
1213 1209 prof.dump_stats(dump_file)
1214 1210 print '\n*** Profile stats marshalled to file',\
1215 1211 `dump_file`+'.',sys_exit
1216 1212 if text_file:
1217 1213 file(text_file,'w').write(output)
1218 1214 print '\n*** Profile printout saved to text file',\
1219 1215 `text_file`+'.',sys_exit
1220 1216
1221 1217 if opts.has_key('r'):
1222 1218 return stats
1223 1219 else:
1224 1220 return None
1225 1221
1226 1222 def magic_run(self, parameter_s ='',runner=None):
1227 1223 """Run the named file inside IPython as a program.
1228 1224
1229 1225 Usage:\\
1230 1226 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1231 1227
1232 1228 Parameters after the filename are passed as command-line arguments to
1233 1229 the program (put in sys.argv). Then, control returns to IPython's
1234 1230 prompt.
1235 1231
1236 1232 This is similar to running at a system prompt:\\
1237 1233 $ python file args\\
1238 1234 but with the advantage of giving you IPython's tracebacks, and of
1239 1235 loading all variables into your interactive namespace for further use
1240 1236 (unless -p is used, see below).
1241 1237
1242 1238 The file is executed in a namespace initially consisting only of
1243 1239 __name__=='__main__' and sys.argv constructed as indicated. It thus
1244 1240 sees its environment as if it were being run as a stand-alone
1245 1241 program. But after execution, the IPython interactive namespace gets
1246 1242 updated with all variables defined in the program (except for __name__
1247 1243 and sys.argv). This allows for very convenient loading of code for
1248 1244 interactive work, while giving each program a 'clean sheet' to run in.
1249 1245
1250 1246 Options:
1251 1247
1252 1248 -n: __name__ is NOT set to '__main__', but to the running file's name
1253 1249 without extension (as python does under import). This allows running
1254 1250 scripts and reloading the definitions in them without calling code
1255 1251 protected by an ' if __name__ == "__main__" ' clause.
1256 1252
1257 1253 -i: run the file in IPython's namespace instead of an empty one. This
1258 1254 is useful if you are experimenting with code written in a text editor
1259 1255 which depends on variables defined interactively.
1260 1256
1261 1257 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1262 1258 being run. This is particularly useful if IPython is being used to
1263 1259 run unittests, which always exit with a sys.exit() call. In such
1264 1260 cases you are interested in the output of the test results, not in
1265 1261 seeing a traceback of the unittest module.
1266 1262
1267 1263 -t: print timing information at the end of the run. IPython will give
1268 1264 you an estimated CPU time consumption for your script, which under
1269 1265 Unix uses the resource module to avoid the wraparound problems of
1270 1266 time.clock(). Under Unix, an estimate of time spent on system tasks
1271 1267 is also given (for Windows platforms this is reported as 0.0).
1272 1268
1273 1269 If -t is given, an additional -N<N> option can be given, where <N>
1274 1270 must be an integer indicating how many times you want the script to
1275 1271 run. The final timing report will include total and per run results.
1276 1272
1277 1273 For example (testing the script uniq_stable.py):
1278 1274
1279 1275 In [1]: run -t uniq_stable
1280 1276
1281 1277 IPython CPU timings (estimated):\\
1282 1278 User : 0.19597 s.\\
1283 1279 System: 0.0 s.\\
1284 1280
1285 1281 In [2]: run -t -N5 uniq_stable
1286 1282
1287 1283 IPython CPU timings (estimated):\\
1288 1284 Total runs performed: 5\\
1289 1285 Times : Total Per run\\
1290 1286 User : 0.910862 s, 0.1821724 s.\\
1291 1287 System: 0.0 s, 0.0 s.
1292 1288
1293 1289 -d: run your program under the control of pdb, the Python debugger.
1294 1290 This allows you to execute your program step by step, watch variables,
1295 1291 etc. Internally, what IPython does is similar to calling:
1296 1292
1297 1293 pdb.run('execfile("YOURFILENAME")')
1298 1294
1299 1295 with a breakpoint set on line 1 of your file. You can change the line
1300 1296 number for this automatic breakpoint to be <N> by using the -bN option
1301 1297 (where N must be an integer). For example:
1302 1298
1303 1299 %run -d -b40 myscript
1304 1300
1305 1301 will set the first breakpoint at line 40 in myscript.py. Note that
1306 1302 the first breakpoint must be set on a line which actually does
1307 1303 something (not a comment or docstring) for it to stop execution.
1308 1304
1309 1305 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1310 1306 first enter 'c' (without qoutes) to start execution up to the first
1311 1307 breakpoint.
1312 1308
1313 1309 Entering 'help' gives information about the use of the debugger. You
1314 1310 can easily see pdb's full documentation with "import pdb;pdb.help()"
1315 1311 at a prompt.
1316 1312
1317 1313 -p: run program under the control of the Python profiler module (which
1318 1314 prints a detailed report of execution times, function calls, etc).
1319 1315
1320 1316 You can pass other options after -p which affect the behavior of the
1321 1317 profiler itself. See the docs for %prun for details.
1322 1318
1323 1319 In this mode, the program's variables do NOT propagate back to the
1324 1320 IPython interactive namespace (because they remain in the namespace
1325 1321 where the profiler executes them).
1326 1322
1327 1323 Internally this triggers a call to %prun, see its documentation for
1328 1324 details on the options available specifically for profiling."""
1329 1325
1330 1326 # get arguments and set sys.argv for program to be run.
1331 1327 opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e',
1332 1328 mode='list',list_all=1)
1333 1329
1334 1330 try:
1335 1331 filename = get_py_filename(arg_lst[0])
1336 1332 except IndexError:
1337 1333 warn('you must provide at least a filename.')
1338 1334 print '\n%run:\n',OInspect.getdoc(self.magic_run)
1339 1335 return
1340 1336 except IOError,msg:
1341 1337 error(msg)
1342 1338 return
1343 1339
1344 1340 # Control the response to exit() calls made by the script being run
1345 1341 exit_ignore = opts.has_key('e')
1346 1342
1347 1343 # Make sure that the running script gets a proper sys.argv as if it
1348 1344 # were run from a system shell.
1349 1345 save_argv = sys.argv # save it for later restoring
1350 1346 sys.argv = [filename]+ arg_lst[1:] # put in the proper filename
1351 1347
1352 1348 if opts.has_key('i'):
1353 1349 prog_ns = self.shell.user_ns
1354 1350 __name__save = self.shell.user_ns['__name__']
1355 1351 prog_ns['__name__'] = '__main__'
1356 1352 else:
1357 1353 if opts.has_key('n'):
1358 1354 name = os.path.splitext(os.path.basename(filename))[0]
1359 1355 else:
1360 1356 name = '__main__'
1361 1357 prog_ns = {'__name__':name}
1362 1358
1363 1359 # pickle fix. See iplib for an explanation
1364 1360 sys.modules[prog_ns['__name__']] = FakeModule(prog_ns)
1365 1361
1366 1362 stats = None
1367 1363 try:
1368 1364 if opts.has_key('p'):
1369 1365 stats = self.magic_prun('',0,opts,arg_lst,prog_ns)
1370 1366 else:
1371 1367 if opts.has_key('d'):
1372 1368 deb = Debugger.Pdb(self.shell.rc.colors)
1373 1369 # reset Breakpoint state, which is moronically kept
1374 1370 # in a class
1375 1371 bdb.Breakpoint.next = 1
1376 1372 bdb.Breakpoint.bplist = {}
1377 1373 bdb.Breakpoint.bpbynumber = [None]
1378 1374 # Set an initial breakpoint to stop execution
1379 1375 maxtries = 10
1380 1376 bp = int(opts.get('b',[1])[0])
1381 1377 checkline = deb.checkline(filename,bp)
1382 1378 if not checkline:
1383 1379 for bp in range(bp+1,bp+maxtries+1):
1384 1380 if deb.checkline(filename,bp):
1385 1381 break
1386 1382 else:
1387 1383 msg = ("\nI failed to find a valid line to set "
1388 1384 "a breakpoint\n"
1389 1385 "after trying up to line: %s.\n"
1390 1386 "Please set a valid breakpoint manually "
1391 1387 "with the -b option." % bp)
1392 1388 error(msg)
1393 1389 return
1394 1390 # if we find a good linenumber, set the breakpoint
1395 1391 deb.do_break('%s:%s' % (filename,bp))
1396 1392 # Start file run
1397 1393 print "NOTE: Enter 'c' at the",
1398 1394 print "ipdb> prompt to start your script."
1399 1395 try:
1400 1396 deb.run('execfile("%s")' % filename,prog_ns)
1401 1397 except:
1402 1398 etype, value, tb = sys.exc_info()
1403 1399 # Skip three frames in the traceback: the %run one,
1404 1400 # one inside bdb.py, and the command-line typed by the
1405 1401 # user (run by exec in pdb itself).
1406 1402 self.shell.InteractiveTB(etype,value,tb,tb_offset=3)
1407 1403 else:
1408 1404 if runner is None:
1409 1405 runner = self.shell.safe_execfile
1410 1406 if opts.has_key('t'):
1411 1407 try:
1412 1408 nruns = int(opts['N'][0])
1413 1409 if nruns < 1:
1414 1410 error('Number of runs must be >=1')
1415 1411 return
1416 1412 except (KeyError):
1417 1413 nruns = 1
1418 1414 if nruns == 1:
1419 1415 t0 = clock2()
1420 1416 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1421 1417 t1 = clock2()
1422 1418 t_usr = t1[0]-t0[0]
1423 1419 t_sys = t1[1]-t1[1]
1424 1420 print "\nIPython CPU timings (estimated):"
1425 1421 print " User : %10s s." % t_usr
1426 1422 print " System: %10s s." % t_sys
1427 1423 else:
1428 1424 runs = range(nruns)
1429 1425 t0 = clock2()
1430 1426 for nr in runs:
1431 1427 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1432 1428 t1 = clock2()
1433 1429 t_usr = t1[0]-t0[0]
1434 1430 t_sys = t1[1]-t1[1]
1435 1431 print "\nIPython CPU timings (estimated):"
1436 1432 print "Total runs performed:",nruns
1437 1433 print " Times : %10s %10s" % ('Total','Per run')
1438 1434 print " User : %10s s, %10s s." % (t_usr,t_usr/nruns)
1439 1435 print " System: %10s s, %10s s." % (t_sys,t_sys/nruns)
1440 1436
1441 1437 else:
1442 1438 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1443 1439 if opts.has_key('i'):
1444 1440 self.shell.user_ns['__name__'] = __name__save
1445 1441 else:
1446 1442 # update IPython interactive namespace
1447 1443 del prog_ns['__name__']
1448 1444 self.shell.user_ns.update(prog_ns)
1449 1445 finally:
1450 1446 sys.argv = save_argv
1451 1447 return stats
1452 1448
1453 1449 def magic_runlog(self, parameter_s =''):
1454 1450 """Run files as logs.
1455 1451
1456 1452 Usage:\\
1457 1453 %runlog file1 file2 ...
1458 1454
1459 1455 Run the named files (treating them as log files) in sequence inside
1460 1456 the interpreter, and return to the prompt. This is much slower than
1461 1457 %run because each line is executed in a try/except block, but it
1462 1458 allows running files with syntax errors in them.
1463 1459
1464 1460 Normally IPython will guess when a file is one of its own logfiles, so
1465 1461 you can typically use %run even for logs. This shorthand allows you to
1466 1462 force any file to be treated as a log file."""
1467 1463
1468 1464 for f in parameter_s.split():
1469 1465 self.shell.safe_execfile(f,self.shell.user_ns,
1470 1466 self.shell.user_ns,islog=1)
1471 1467
1472 1468 def magic_time(self,parameter_s = ''):
1473 1469 """Time execution of a Python statement or expression.
1474 1470
1475 1471 The CPU and wall clock times are printed, and the value of the
1476 1472 expression (if any) is returned. Note that under Win32, system time
1477 1473 is always reported as 0, since it can not be measured.
1478 1474
1479 1475 This function provides very basic timing functionality. In Python
1480 1476 2.3, the timeit module offers more control and sophistication, but for
1481 1477 now IPython supports Python 2.2, so we can not rely on timeit being
1482 1478 present.
1483 1479
1484 1480 Some examples:
1485 1481
1486 1482 In [1]: time 2**128
1487 1483 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1488 1484 Wall time: 0.00
1489 1485 Out[1]: 340282366920938463463374607431768211456L
1490 1486
1491 1487 In [2]: n = 1000000
1492 1488
1493 1489 In [3]: time sum(range(n))
1494 1490 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1495 1491 Wall time: 1.37
1496 1492 Out[3]: 499999500000L
1497 1493
1498 1494 In [4]: time print 'hello world'
1499 1495 hello world
1500 1496 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1501 1497 Wall time: 0.00
1502 1498 """
1503 1499
1504 1500 # fail immediately if the given expression can't be compiled
1505 1501 try:
1506 1502 mode = 'eval'
1507 1503 code = compile(parameter_s,'<timed eval>',mode)
1508 1504 except SyntaxError:
1509 1505 mode = 'exec'
1510 1506 code = compile(parameter_s,'<timed exec>',mode)
1511 1507 # skew measurement as little as possible
1512 1508 glob = self.shell.user_ns
1513 1509 clk = clock2
1514 1510 wtime = time.time
1515 1511 # time execution
1516 1512 wall_st = wtime()
1517 1513 if mode=='eval':
1518 1514 st = clk()
1519 1515 out = eval(code,glob)
1520 1516 end = clk()
1521 1517 else:
1522 1518 st = clk()
1523 1519 exec code in glob
1524 1520 end = clk()
1525 1521 out = None
1526 1522 wall_end = wtime()
1527 1523 # Compute actual times and report
1528 1524 wall_time = wall_end-wall_st
1529 1525 cpu_user = end[0]-st[0]
1530 1526 cpu_sys = end[1]-st[1]
1531 1527 cpu_tot = cpu_user+cpu_sys
1532 1528 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
1533 1529 (cpu_user,cpu_sys,cpu_tot)
1534 1530 print "Wall time: %.2f" % wall_time
1535 1531 return out
1536 1532
1537 1533 def magic_macro(self,parameter_s = ''):
1538 1534 """Define a set of input lines as a macro for future re-execution.
1539 1535
1540 1536 Usage:\\
1541 1537 %macro name n1:n2 n3:n4 ... n5 .. n6 ...
1542 1538
1543 1539 This will define a global variable called `name` which is a string
1544 1540 made of joining the slices and lines you specify (n1,n2,... numbers
1545 1541 above) from your input history into a single string. This variable
1546 1542 acts like an automatic function which re-executes those lines as if
1547 1543 you had typed them. You just type 'name' at the prompt and the code
1548 1544 executes.
1549 1545
1550 1546 Note that the slices use the standard Python slicing notation (5:8
1551 1547 means include lines numbered 5,6,7).
1552 1548
1553 1549 For example, if your history contains (%hist prints it):
1554 1550
1555 1551 44: x=1\\
1556 1552 45: y=3\\
1557 1553 46: z=x+y\\
1558 1554 47: print x\\
1559 1555 48: a=5\\
1560 1556 49: print 'x',x,'y',y\\
1561 1557
1562 1558 you can create a macro with lines 44 through 47 (included) and line 49
1563 1559 called my_macro with:
1564 1560
1565 1561 In [51]: %macro my_macro 44:48 49
1566 1562
1567 1563 Now, typing `my_macro` (without quotes) will re-execute all this code
1568 1564 in one pass.
1569 1565
1570 1566 You don't need to give the line-numbers in order, and any given line
1571 1567 number can appear multiple times. You can assemble macros with any
1572 1568 lines from your input history in any order.
1573 1569
1574 1570 The macro is a simple object which holds its value in an attribute,
1575 1571 but IPython's display system checks for macros and executes them as
1576 1572 code instead of printing them when you type their name.
1577 1573
1578 1574 You can view a macro's contents by explicitly printing it with:
1579 1575
1580 1576 'print macro_name'.
1581 1577
1582 1578 For one-off cases which DON'T contain magic function calls in them you
1583 1579 can obtain similar results by explicitly executing slices from your
1584 1580 input history with:
1585 1581
1586 1582 In [60]: exec In[44:48]+In[49]"""
1587 1583
1588 1584 args = parameter_s.split()
1589 1585 name,ranges = args[0], args[1:]
1590 1586 #print 'rng',ranges # dbg
1591 1587 lines = self.extract_input_slices(ranges)
1592 1588 macro = Macro(lines)
1593 1589 self.shell.user_ns.update({name:macro})
1594 1590 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
1595 1591 print 'Macro contents:'
1596 print macro
1592 print macro,
1597 1593
1598 1594 def magic_save(self,parameter_s = ''):
1599 1595 """Save a set of lines to a given filename.
1600 1596
1601 1597 Usage:\\
1602 1598 %save filename n1:n2 n3:n4 ... n5 .. n6 ...
1603 1599
1604 1600 This function uses the same syntax as %macro for line extraction, but
1605 1601 instead of creating a macro it saves the resulting string to the
1606 1602 filename you specify.
1607 1603
1608 1604 It adds a '.py' extension to the file if you don't do so yourself, and
1609 1605 it asks for confirmation before overwriting existing files."""
1610 1606
1611 1607 args = parameter_s.split()
1612 1608 fname,ranges = args[0], args[1:]
1613 1609 if not fname.endswith('.py'):
1614 1610 fname += '.py'
1615 1611 if os.path.isfile(fname):
1616 1612 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
1617 1613 if ans.lower() not in ['y','yes']:
1618 1614 print 'Operation cancelled.'
1619 1615 return
1620 1616 cmds = ''.join(self.extract_input_slices(ranges))
1621 1617 f = file(fname,'w')
1622 1618 f.write(cmds)
1623 1619 f.close()
1624 1620 print 'The following commands were written to file `%s`:' % fname
1625 1621 print cmds
1626 1622
1627 1623 def magic_ed(self,parameter_s = ''):
1628 1624 """Alias to %edit."""
1629 1625 return self.magic_edit(parameter_s)
1630 1626
1631 1627 def magic_edit(self,parameter_s = '',last_call=['','']):
1632 1628 """Bring up an editor and execute the resulting code.
1633 1629
1634 1630 Usage:
1635 1631 %edit [options] [args]
1636 1632
1637 1633 %edit runs IPython's editor hook. The default version of this hook is
1638 1634 set to call the __IPYTHON__.rc.editor command. This is read from your
1639 1635 environment variable $EDITOR. If this isn't found, it will default to
1640 1636 vi under Linux/Unix and to notepad under Windows. See the end of this
1641 1637 docstring for how to change the editor hook.
1642 1638
1643 1639 You can also set the value of this editor via the command line option
1644 1640 '-editor' or in your ipythonrc file. This is useful if you wish to use
1645 1641 specifically for IPython an editor different from your typical default
1646 1642 (and for Windows users who typically don't set environment variables).
1647 1643
1648 1644 This command allows you to conveniently edit multi-line code right in
1649 1645 your IPython session.
1650 1646
1651 1647 If called without arguments, %edit opens up an empty editor with a
1652 1648 temporary file and will execute the contents of this file when you
1653 1649 close it (don't forget to save it!).
1654 1650
1655 1651 Options:
1656 1652
1657 1653 -p: this will call the editor with the same data as the previous time
1658 1654 it was used, regardless of how long ago (in your current session) it
1659 1655 was.
1660 1656
1661 1657 -x: do not execute the edited code immediately upon exit. This is
1662 1658 mainly useful if you are editing programs which need to be called with
1663 1659 command line arguments, which you can then do using %run.
1664 1660
1665 1661 Arguments:
1666 1662
1667 1663 If arguments are given, the following possibilites exist:
1668 1664
1669 1665 - The arguments are numbers or pairs of colon-separated numbers (like
1670 1666 1 4:8 9). These are interpreted as lines of previous input to be
1671 1667 loaded into the editor. The syntax is the same of the %macro command.
1672 1668
1673 1669 - If the argument doesn't start with a number, it is evaluated as a
1674 1670 variable and its contents loaded into the editor. You can thus edit
1675 1671 any string which contains python code (including the result of
1676 1672 previous edits).
1677 1673
1678 1674 - If the argument is the name of an object (other than a string),
1679 1675 IPython will try to locate the file where it was defined and open the
1680 1676 editor at the point where it is defined. You can use `%edit function`
1681 1677 to load an editor exactly at the point where 'function' is defined,
1682 1678 edit it and have the file be executed automatically.
1683 1679
1684 1680 Note: opening at an exact line is only supported under Unix, and some
1685 1681 editors (like kedit and gedit up to Gnome 2.8) do not understand the
1686 1682 '+NUMBER' parameter necessary for this feature. Good editors like
1687 1683 (X)Emacs, vi, jed, pico and joe all do.
1688 1684
1689 1685 - If the argument is not found as a variable, IPython will look for a
1690 1686 file with that name (adding .py if necessary) and load it into the
1691 1687 editor. It will execute its contents with execfile() when you exit,
1692 1688 loading any code in the file into your interactive namespace.
1693 1689
1694 1690 After executing your code, %edit will return as output the code you
1695 1691 typed in the editor (except when it was an existing file). This way
1696 1692 you can reload the code in further invocations of %edit as a variable,
1697 1693 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
1698 1694 the output.
1699 1695
1700 1696 Note that %edit is also available through the alias %ed.
1701 1697
1702 1698 This is an example of creating a simple function inside the editor and
1703 1699 then modifying it. First, start up the editor:
1704 1700
1705 1701 In [1]: ed\\
1706 1702 Editing... done. Executing edited code...\\
1707 1703 Out[1]: 'def foo():\\n print "foo() was defined in an editing session"\\n'
1708 1704
1709 1705 We can then call the function foo():
1710 1706
1711 1707 In [2]: foo()\\
1712 1708 foo() was defined in an editing session
1713 1709
1714 1710 Now we edit foo. IPython automatically loads the editor with the
1715 1711 (temporary) file where foo() was previously defined:
1716 1712
1717 1713 In [3]: ed foo\\
1718 1714 Editing... done. Executing edited code...
1719 1715
1720 1716 And if we call foo() again we get the modified version:
1721 1717
1722 1718 In [4]: foo()\\
1723 1719 foo() has now been changed!
1724 1720
1725 1721 Here is an example of how to edit a code snippet successive
1726 1722 times. First we call the editor:
1727 1723
1728 1724 In [8]: ed\\
1729 1725 Editing... done. Executing edited code...\\
1730 1726 hello\\
1731 1727 Out[8]: "print 'hello'\\n"
1732 1728
1733 1729 Now we call it again with the previous output (stored in _):
1734 1730
1735 1731 In [9]: ed _\\
1736 1732 Editing... done. Executing edited code...\\
1737 1733 hello world\\
1738 1734 Out[9]: "print 'hello world'\\n"
1739 1735
1740 1736 Now we call it with the output #8 (stored in _8, also as Out[8]):
1741 1737
1742 1738 In [10]: ed _8\\
1743 1739 Editing... done. Executing edited code...\\
1744 1740 hello again\\
1745 1741 Out[10]: "print 'hello again'\\n"
1746 1742
1747 1743
1748 1744 Changing the default editor hook:
1749 1745
1750 1746 If you wish to write your own editor hook, you can put it in a
1751 1747 configuration file which you load at startup time. The default hook
1752 1748 is defined in the IPython.hooks module, and you can use that as a
1753 1749 starting example for further modifications. That file also has
1754 1750 general instructions on how to set a new hook for use once you've
1755 1751 defined it."""
1756 1752
1757 1753 # FIXME: This function has become a convoluted mess. It needs a
1758 1754 # ground-up rewrite with clean, simple logic.
1759 1755
1760 1756 def make_filename(arg):
1761 1757 "Make a filename from the given args"
1762 1758 try:
1763 1759 filename = get_py_filename(arg)
1764 1760 except IOError:
1765 1761 if args.endswith('.py'):
1766 1762 filename = arg
1767 1763 else:
1768 1764 filename = None
1769 1765 return filename
1770 1766
1771 1767 # custom exceptions
1772 1768 class DataIsObject(Exception): pass
1773 1769
1774 1770 opts,args = self.parse_options(parameter_s,'px')
1775 1771
1776 1772 # Default line number value
1777 1773 lineno = None
1778 1774 if opts.has_key('p'):
1779 1775 args = '_%s' % last_call[0]
1780 1776 if not self.shell.user_ns.has_key(args):
1781 1777 args = last_call[1]
1782 1778
1783 1779 # use last_call to remember the state of the previous call, but don't
1784 1780 # let it be clobbered by successive '-p' calls.
1785 1781 try:
1786 1782 last_call[0] = self.shell.outputcache.prompt_count
1787 1783 if not opts.has_key('p'):
1788 1784 last_call[1] = parameter_s
1789 1785 except:
1790 1786 pass
1791 1787
1792 1788 # by default this is done with temp files, except when the given
1793 1789 # arg is a filename
1794 1790 use_temp = 1
1795 1791
1796 1792 if re.match(r'\d',args):
1797 1793 # Mode where user specifies ranges of lines, like in %macro.
1798 1794 # This means that you can't edit files whose names begin with
1799 1795 # numbers this way. Tough.
1800 1796 ranges = args.split()
1801 1797 data = ''.join(self.extract_input_slices(ranges))
1802 1798 elif args.endswith('.py'):
1803 1799 filename = make_filename(args)
1804 1800 data = ''
1805 1801 use_temp = 0
1806 1802 elif args:
1807 1803 try:
1808 1804 # Load the parameter given as a variable. If not a string,
1809 1805 # process it as an object instead (below)
1810 1806
1811 1807 #print '*** args',args,'type',type(args) # dbg
1812 1808 data = eval(args,self.shell.user_ns)
1813 1809 if not type(data) in StringTypes:
1814 1810 raise DataIsObject
1815 1811 except (NameError,SyntaxError):
1816 1812 # given argument is not a variable, try as a filename
1817 1813 filename = make_filename(args)
1818 1814 if filename is None:
1819 1815 warn("Argument given (%s) can't be found as a variable "
1820 1816 "or as a filename." % args)
1821 1817 return
1822 1818 data = ''
1823 1819 use_temp = 0
1824 1820 except DataIsObject:
1825 1821 # For objects, try to edit the file where they are defined
1826 1822 try:
1827 1823 filename = inspect.getabsfile(data)
1828 1824 datafile = 1
1829 1825 except TypeError:
1830 1826 filename = make_filename(args)
1831 1827 datafile = 1
1832 1828 warn('Could not find file where `%s` is defined.\n'
1833 1829 'Opening a file named `%s`' % (args,filename))
1834 1830 # Now, make sure we can actually read the source (if it was in
1835 1831 # a temp file it's gone by now).
1836 1832 if datafile:
1837 1833 try:
1838 1834 lineno = inspect.getsourcelines(data)[1]
1839 1835 except IOError:
1840 1836 filename = make_filename(args)
1841 1837 if filename is None:
1842 1838 warn('The file `%s` where `%s` was defined cannot '
1843 1839 'be read.' % (filename,data))
1844 1840 return
1845 1841 use_temp = 0
1846 1842 else:
1847 1843 data = ''
1848 1844
1849 1845 if use_temp:
1850 1846 filename = tempfile.mktemp('.py')
1851 1847 self.shell.tempfiles.append(filename)
1852 1848
1853 1849 if data and use_temp:
1854 1850 tmp_file = open(filename,'w')
1855 1851 tmp_file.write(data)
1856 1852 tmp_file.close()
1857 1853
1858 1854 # do actual editing here
1859 1855 print 'Editing...',
1860 1856 sys.stdout.flush()
1861 1857 self.shell.hooks.editor(filename,lineno)
1862 1858 if opts.has_key('x'): # -x prevents actual execution
1863 1859 print
1864 1860 else:
1865 1861 print 'done. Executing edited code...'
1866 1862 try:
1867 1863 self.shell.safe_execfile(filename,self.shell.user_ns)
1868 1864 except IOError,msg:
1869 1865 if msg.filename == filename:
1870 1866 warn('File not found. Did you forget to save?')
1871 1867 return
1872 1868 else:
1873 1869 self.shell.showtraceback()
1874 1870 except:
1875 1871 self.shell.showtraceback()
1876 1872 if use_temp:
1877 1873 contents = open(filename).read()
1878 1874 return contents
1879 1875
1880 1876 def magic_xmode(self,parameter_s = ''):
1881 1877 """Switch modes for the exception handlers.
1882 1878
1883 1879 Valid modes: Plain, Context and Verbose.
1884 1880
1885 1881 If called without arguments, acts as a toggle."""
1886 1882
1887 1883 def xmode_switch_err(name):
1888 1884 warn('Error changing %s exception modes.\n%s' %
1889 1885 (name,sys.exc_info()[1]))
1890 1886
1891 1887 shell = self.shell
1892 1888 new_mode = parameter_s.strip().capitalize()
1893 1889 try:
1894 1890 shell.InteractiveTB.set_mode(mode=new_mode)
1895 1891 print 'Exception reporting mode:',shell.InteractiveTB.mode
1896 1892 except:
1897 1893 xmode_switch_err('user')
1898 1894
1899 1895 # threaded shells use a special handler in sys.excepthook
1900 1896 if shell.isthreaded:
1901 1897 try:
1902 1898 shell.sys_excepthook.set_mode(mode=new_mode)
1903 1899 except:
1904 1900 xmode_switch_err('threaded')
1905 1901
1906 1902 def magic_colors(self,parameter_s = ''):
1907 1903 """Switch color scheme for prompts, info system and exception handlers.
1908 1904
1909 1905 Currently implemented schemes: NoColor, Linux, LightBG.
1910 1906
1911 1907 Color scheme names are not case-sensitive."""
1912 1908
1913 1909 def color_switch_err(name):
1914 1910 warn('Error changing %s color schemes.\n%s' %
1915 1911 (name,sys.exc_info()[1]))
1916 1912
1917 1913
1918 1914 new_scheme = parameter_s.strip()
1919 1915 if not new_scheme:
1920 1916 print 'You must specify a color scheme.'
1921 1917 return
1922 1918 # Under Windows, check for Gary Bishop's readline, which is necessary
1923 1919 # for ANSI coloring
1924 1920 if os.name in ['nt','dos']:
1925 1921 try:
1926 1922 import readline
1927 1923 except ImportError:
1928 1924 has_readline = 0
1929 1925 else:
1930 1926 try:
1931 1927 readline.GetOutputFile()
1932 1928 except AttributeError:
1933 1929 has_readline = 0
1934 1930 else:
1935 1931 has_readline = 1
1936 1932 if not has_readline:
1937 1933 msg = """\
1938 1934 Proper color support under MS Windows requires Gary Bishop's readline library.
1939 1935 You can find it at:
1940 1936 http://sourceforge.net/projects/uncpythontools
1941 1937 Gary's readline needs the ctypes module, from:
1942 1938 http://starship.python.net/crew/theller/ctypes
1943 1939
1944 1940 Defaulting color scheme to 'NoColor'"""
1945 1941 new_scheme = 'NoColor'
1946 1942 warn(msg)
1947 1943 # local shortcut
1948 1944 shell = self.shell
1949 1945
1950 1946 # Set prompt colors
1951 1947 try:
1952 1948 shell.outputcache.set_colors(new_scheme)
1953 1949 except:
1954 1950 color_switch_err('prompt')
1955 1951 else:
1956 1952 shell.rc.colors = \
1957 1953 shell.outputcache.color_table.active_scheme_name
1958 1954 # Set exception colors
1959 1955 try:
1960 1956 shell.InteractiveTB.set_colors(scheme = new_scheme)
1961 1957 shell.SyntaxTB.set_colors(scheme = new_scheme)
1962 1958 except:
1963 1959 color_switch_err('exception')
1964 1960
1965 1961 # threaded shells use a verbose traceback in sys.excepthook
1966 1962 if shell.isthreaded:
1967 1963 try:
1968 1964 shell.sys_excepthook.set_colors(scheme=new_scheme)
1969 1965 except:
1970 1966 color_switch_err('system exception handler')
1971 1967
1972 1968 # Set info (for 'object?') colors
1973 1969 if shell.rc.color_info:
1974 1970 try:
1975 1971 shell.inspector.set_active_scheme(new_scheme)
1976 1972 except:
1977 1973 color_switch_err('object inspector')
1978 1974 else:
1979 1975 shell.inspector.set_active_scheme('NoColor')
1980 1976
1981 1977 def magic_color_info(self,parameter_s = ''):
1982 1978 """Toggle color_info.
1983 1979
1984 1980 The color_info configuration parameter controls whether colors are
1985 1981 used for displaying object details (by things like %psource, %pfile or
1986 1982 the '?' system). This function toggles this value with each call.
1987 1983
1988 1984 Note that unless you have a fairly recent pager (less works better
1989 1985 than more) in your system, using colored object information displays
1990 1986 will not work properly. Test it and see."""
1991 1987
1992 1988 self.shell.rc.color_info = 1 - self.shell.rc.color_info
1993 1989 self.magic_colors(self.shell.rc.colors)
1994 1990 print 'Object introspection functions have now coloring:',
1995 1991 print ['OFF','ON'][self.shell.rc.color_info]
1996 1992
1997 1993 def magic_Pprint(self, parameter_s=''):
1998 1994 """Toggle pretty printing on/off."""
1999 1995
2000 1996 self.shell.outputcache.Pprint = 1 - self.shell.outputcache.Pprint
2001 1997 print 'Pretty printing has been turned', \
2002 1998 ['OFF','ON'][self.shell.outputcache.Pprint]
2003 1999
2004 2000 def magic_exit(self, parameter_s=''):
2005 2001 """Exit IPython, confirming if configured to do so.
2006 2002
2007 2003 You can configure whether IPython asks for confirmation upon exit by
2008 2004 setting the confirm_exit flag in the ipythonrc file."""
2009 2005
2010 2006 self.shell.exit()
2011 2007
2012 2008 def magic_quit(self, parameter_s=''):
2013 2009 """Exit IPython, confirming if configured to do so (like %exit)"""
2014 2010
2015 2011 self.shell.exit()
2016 2012
2017 2013 def magic_Exit(self, parameter_s=''):
2018 2014 """Exit IPython without confirmation."""
2019 2015
2020 2016 self.shell.exit_now = True
2021 2017
2022 2018 def magic_Quit(self, parameter_s=''):
2023 2019 """Exit IPython without confirmation (like %Exit)."""
2024 2020
2025 2021 self.shell.exit_now = True
2026 2022
2027 2023 #......................................................................
2028 2024 # Functions to implement unix shell-type things
2029 2025
2030 2026 def magic_alias(self, parameter_s = ''):
2031 2027 """Define an alias for a system command.
2032 2028
2033 2029 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
2034 2030
2035 2031 Then, typing 'alias_name params' will execute the system command 'cmd
2036 2032 params' (from your underlying operating system).
2037 2033
2038 2034 Aliases have lower precedence than magic functions and Python normal
2039 2035 variables, so if 'foo' is both a Python variable and an alias, the
2040 2036 alias can not be executed until 'del foo' removes the Python variable.
2041 2037
2042 2038 You can use the %l specifier in an alias definition to represent the
2043 2039 whole line when the alias is called. For example:
2044 2040
2045 2041 In [2]: alias all echo "Input in brackets: <%l>"\\
2046 2042 In [3]: all hello world\\
2047 2043 Input in brackets: <hello world>
2048 2044
2049 2045 You can also define aliases with parameters using %s specifiers (one
2050 2046 per parameter):
2051 2047
2052 2048 In [1]: alias parts echo first %s second %s\\
2053 2049 In [2]: %parts A B\\
2054 2050 first A second B\\
2055 2051 In [3]: %parts A\\
2056 2052 Incorrect number of arguments: 2 expected.\\
2057 2053 parts is an alias to: 'echo first %s second %s'
2058 2054
2059 2055 Note that %l and %s are mutually exclusive. You can only use one or
2060 2056 the other in your aliases.
2061 2057
2062 2058 Aliases expand Python variables just like system calls using ! or !!
2063 2059 do: all expressions prefixed with '$' get expanded. For details of
2064 2060 the semantic rules, see PEP-215:
2065 2061 http://www.python.org/peps/pep-0215.html. This is the library used by
2066 2062 IPython for variable expansion. If you want to access a true shell
2067 2063 variable, an extra $ is necessary to prevent its expansion by IPython:
2068 2064
2069 2065 In [6]: alias show echo\\
2070 2066 In [7]: PATH='A Python string'\\
2071 2067 In [8]: show $PATH\\
2072 2068 A Python string\\
2073 2069 In [9]: show $$PATH\\
2074 2070 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2075 2071
2076 2072 You can use the alias facility to acess all of $PATH. See the %rehash
2077 2073 and %rehashx functions, which automatically create aliases for the
2078 2074 contents of your $PATH.
2079 2075
2080 2076 If called with no parameters, %alias prints the current alias table."""
2081 2077
2082 2078 par = parameter_s.strip()
2083 2079 if not par:
2084 2080 if self.shell.rc.automagic:
2085 2081 prechar = ''
2086 2082 else:
2087 2083 prechar = self.shell.ESC_MAGIC
2088 2084 print 'Alias\t\tSystem Command\n'+'-'*30
2089 2085 atab = self.shell.alias_table
2090 2086 aliases = atab.keys()
2091 2087 aliases.sort()
2092 2088 for alias in aliases:
2093 2089 print prechar+alias+'\t\t'+atab[alias][1]
2094 2090 print '-'*30+'\nTotal number of aliases:',len(aliases)
2095 2091 return
2096 2092 try:
2097 2093 alias,cmd = par.split(None,1)
2098 2094 except:
2099 2095 print OInspect.getdoc(self.magic_alias)
2100 2096 else:
2101 2097 nargs = cmd.count('%s')
2102 2098 if nargs>0 and cmd.find('%l')>=0:
2103 2099 error('The %s and %l specifiers are mutually exclusive '
2104 2100 'in alias definitions.')
2105 2101 else: # all looks OK
2106 2102 self.shell.alias_table[alias] = (nargs,cmd)
2107 2103 self.shell.alias_table_validate(verbose=1)
2108 2104 # end magic_alias
2109 2105
2110 2106 def magic_unalias(self, parameter_s = ''):
2111 2107 """Remove an alias"""
2112 2108
2113 2109 aname = parameter_s.strip()
2114 2110 if aname in self.shell.alias_table:
2115 2111 del self.shell.alias_table[aname]
2116 2112
2117 2113 def magic_rehash(self, parameter_s = ''):
2118 2114 """Update the alias table with all entries in $PATH.
2119 2115
2120 2116 This version does no checks on execute permissions or whether the
2121 2117 contents of $PATH are truly files (instead of directories or something
2122 2118 else). For such a safer (but slower) version, use %rehashx."""
2123 2119
2124 2120 # This function (and rehashx) manipulate the alias_table directly
2125 2121 # rather than calling magic_alias, for speed reasons. A rehash on a
2126 2122 # typical Linux box involves several thousand entries, so efficiency
2127 2123 # here is a top concern.
2128 2124
2129 2125 path = filter(os.path.isdir,os.environ['PATH'].split(os.pathsep))
2130 2126 alias_table = self.shell.alias_table
2131 2127 for pdir in path:
2132 2128 for ff in os.listdir(pdir):
2133 2129 # each entry in the alias table must be (N,name), where
2134 2130 # N is the number of positional arguments of the alias.
2135 2131 alias_table[ff] = (0,ff)
2136 2132 # Make sure the alias table doesn't contain keywords or builtins
2137 2133 self.shell.alias_table_validate()
2138 2134 # Call again init_auto_alias() so we get 'rm -i' and other modified
2139 2135 # aliases since %rehash will probably clobber them
2140 2136 self.shell.init_auto_alias()
2141 2137
2142 2138 def magic_rehashx(self, parameter_s = ''):
2143 2139 """Update the alias table with all executable files in $PATH.
2144 2140
2145 2141 This version explicitly checks that every entry in $PATH is a file
2146 2142 with execute access (os.X_OK), so it is much slower than %rehash.
2147 2143
2148 2144 Under Windows, it checks executability as a match agains a
2149 2145 '|'-separated string of extensions, stored in the IPython config
2150 2146 variable win_exec_ext. This defaults to 'exe|com|bat'. """
2151 2147
2152 2148 path = filter(os.path.isdir,os.environ['PATH'].split(os.pathsep))
2153 2149 alias_table = self.shell.alias_table
2154 2150
2155 2151 if os.name == 'posix':
2156 2152 isexec = lambda fname:os.path.isfile(fname) and \
2157 2153 os.access(fname,os.X_OK)
2158 2154 else:
2159 2155
2160 2156 try:
2161 2157 winext = os.environ['pathext'].replace(';','|').replace('.','')
2162 2158 except KeyError:
2163 2159 winext = 'exe|com|bat'
2164 2160
2165 2161 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2166 2162 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2167 2163 savedir = os.getcwd()
2168 2164 try:
2169 2165 # write the whole loop for posix/Windows so we don't have an if in
2170 2166 # the innermost part
2171 2167 if os.name == 'posix':
2172 2168 for pdir in path:
2173 2169 os.chdir(pdir)
2174 2170 for ff in os.listdir(pdir):
2175 2171 if isexec(ff):
2176 2172 # each entry in the alias table must be (N,name),
2177 2173 # where N is the number of positional arguments of the
2178 2174 # alias.
2179 2175 alias_table[ff] = (0,ff)
2180 2176 else:
2181 2177 for pdir in path:
2182 2178 os.chdir(pdir)
2183 2179 for ff in os.listdir(pdir):
2184 2180 if isexec(ff):
2185 2181 alias_table[execre.sub(r'\1',ff)] = (0,ff)
2186 2182 # Make sure the alias table doesn't contain keywords or builtins
2187 2183 self.shell.alias_table_validate()
2188 2184 # Call again init_auto_alias() so we get 'rm -i' and other
2189 2185 # modified aliases since %rehashx will probably clobber them
2190 2186 self.shell.init_auto_alias()
2191 2187 finally:
2192 2188 os.chdir(savedir)
2193 2189
2194 2190 def magic_pwd(self, parameter_s = ''):
2195 2191 """Return the current working directory path."""
2196 2192 return os.getcwd()
2197 2193
2198 2194 def magic_cd(self, parameter_s=''):
2199 2195 """Change the current working directory.
2200 2196
2201 2197 This command automatically maintains an internal list of directories
2202 2198 you visit during your IPython session, in the variable _dh. The
2203 2199 command %dhist shows this history nicely formatted.
2204 2200
2205 2201 Usage:
2206 2202
2207 2203 cd 'dir': changes to directory 'dir'.
2208 2204
2209 2205 cd -: changes to the last visited directory.
2210 2206
2211 2207 cd -<n>: changes to the n-th directory in the directory history.
2212 2208
2213 2209 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
2214 2210 (note: cd <bookmark_name> is enough if there is no
2215 2211 directory <bookmark_name>, but a bookmark with the name exists.)
2216 2212
2217 2213 Options:
2218 2214
2219 2215 -q: quiet. Do not print the working directory after the cd command is
2220 2216 executed. By default IPython's cd command does print this directory,
2221 2217 since the default prompts do not display path information.
2222 2218
2223 2219 Note that !cd doesn't work for this purpose because the shell where
2224 2220 !command runs is immediately discarded after executing 'command'."""
2225 2221
2226 2222 parameter_s = parameter_s.strip()
2227 2223 bkms = self.shell.persist.get("bookmarks",{})
2228 2224
2229 2225 numcd = re.match(r'(-)(\d+)$',parameter_s)
2230 2226 # jump in directory history by number
2231 2227 if numcd:
2232 2228 nn = int(numcd.group(2))
2233 2229 try:
2234 2230 ps = self.shell.user_ns['_dh'][nn]
2235 2231 except IndexError:
2236 2232 print 'The requested directory does not exist in history.'
2237 2233 return
2238 2234 else:
2239 2235 opts = {}
2240 2236 else:
2241 2237 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
2242 2238 # jump to previous
2243 2239 if ps == '-':
2244 2240 try:
2245 2241 ps = self.shell.user_ns['_dh'][-2]
2246 2242 except IndexError:
2247 2243 print 'No previous directory to change to.'
2248 2244 return
2249 2245 # jump to bookmark
2250 2246 elif opts.has_key('b') or (bkms.has_key(ps) and not os.path.isdir(ps)):
2251 2247 if bkms.has_key(ps):
2252 2248 target = bkms[ps]
2253 2249 print '(bookmark:%s) -> %s' % (ps,target)
2254 2250 ps = target
2255 2251 else:
2256 2252 if bkms:
2257 2253 error("Bookmark '%s' not found. "
2258 2254 "Use '%bookmark -l' to see your bookmarks." % ps)
2259 2255 else:
2260 2256 print "Bookmarks not set - use %bookmark <bookmarkname>"
2261 2257 return
2262 2258
2263 2259 # at this point ps should point to the target dir
2264 2260 if ps:
2265 2261 try:
2266 2262 os.chdir(os.path.expanduser(ps))
2267 2263 except OSError:
2268 2264 print sys.exc_info()[1]
2269 2265 else:
2270 2266 self.shell.user_ns['_dh'].append(os.getcwd())
2271 2267 else:
2272 2268 os.chdir(self.shell.home_dir)
2273 2269 self.shell.user_ns['_dh'].append(os.getcwd())
2274 2270 if not 'q' in opts:
2275 2271 print self.shell.user_ns['_dh'][-1]
2276 2272
2277 2273 def magic_dhist(self, parameter_s=''):
2278 2274 """Print your history of visited directories.
2279 2275
2280 2276 %dhist -> print full history\\
2281 2277 %dhist n -> print last n entries only\\
2282 2278 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
2283 2279
2284 2280 This history is automatically maintained by the %cd command, and
2285 2281 always available as the global list variable _dh. You can use %cd -<n>
2286 2282 to go to directory number <n>."""
2287 2283
2288 2284 dh = self.shell.user_ns['_dh']
2289 2285 if parameter_s:
2290 2286 try:
2291 2287 args = map(int,parameter_s.split())
2292 2288 except:
2293 2289 self.arg_err(Magic.magic_dhist)
2294 2290 return
2295 2291 if len(args) == 1:
2296 2292 ini,fin = max(len(dh)-(args[0]),0),len(dh)
2297 2293 elif len(args) == 2:
2298 2294 ini,fin = args
2299 2295 else:
2300 2296 self.arg_err(Magic.magic_dhist)
2301 2297 return
2302 2298 else:
2303 2299 ini,fin = 0,len(dh)
2304 2300 nlprint(dh,
2305 2301 header = 'Directory history (kept in _dh)',
2306 2302 start=ini,stop=fin)
2307 2303
2308 2304 def magic_env(self, parameter_s=''):
2309 2305 """List environment variables."""
2310 2306
2311 2307 return os.environ.data
2312 2308
2313 2309 def magic_pushd(self, parameter_s=''):
2314 2310 """Place the current dir on stack and change directory.
2315 2311
2316 2312 Usage:\\
2317 2313 %pushd ['dirname']
2318 2314
2319 2315 %pushd with no arguments does a %pushd to your home directory.
2320 2316 """
2321 2317 if parameter_s == '': parameter_s = '~'
2322 2318 dir_s = self.shell.dir_stack
2323 2319 if len(dir_s)>0 and os.path.expanduser(parameter_s) != \
2324 2320 os.path.expanduser(self.shell.dir_stack[0]):
2325 2321 try:
2326 2322 self.magic_cd(parameter_s)
2327 2323 dir_s.insert(0,os.getcwd().replace(self.home_dir,'~'))
2328 2324 self.magic_dirs()
2329 2325 except:
2330 2326 print 'Invalid directory'
2331 2327 else:
2332 2328 print 'You are already there!'
2333 2329
2334 2330 def magic_popd(self, parameter_s=''):
2335 2331 """Change to directory popped off the top of the stack.
2336 2332 """
2337 2333 if len (self.shell.dir_stack) > 1:
2338 2334 self.shell.dir_stack.pop(0)
2339 2335 self.magic_cd(self.shell.dir_stack[0])
2340 2336 print self.shell.dir_stack[0]
2341 2337 else:
2342 2338 print "You can't remove the starting directory from the stack:",\
2343 2339 self.shell.dir_stack
2344 2340
2345 2341 def magic_dirs(self, parameter_s=''):
2346 2342 """Return the current directory stack."""
2347 2343
2348 2344 return self.shell.dir_stack[:]
2349 2345
2350 2346 def magic_sc(self, parameter_s=''):
2351 2347 """Shell capture - execute a shell command and capture its output.
2352 2348
2353 2349 %sc [options] varname=command
2354 2350
2355 2351 IPython will run the given command using commands.getoutput(), and
2356 2352 will then update the user's interactive namespace with a variable
2357 2353 called varname, containing the value of the call. Your command can
2358 2354 contain shell wildcards, pipes, etc.
2359 2355
2360 2356 The '=' sign in the syntax is mandatory, and the variable name you
2361 2357 supply must follow Python's standard conventions for valid names.
2362 2358
2363 2359 Options:
2364 2360
2365 2361 -l: list output. Split the output on newlines into a list before
2366 2362 assigning it to the given variable. By default the output is stored
2367 2363 as a single string.
2368 2364
2369 2365 -v: verbose. Print the contents of the variable.
2370 2366
2371 2367 In most cases you should not need to split as a list, because the
2372 2368 returned value is a special type of string which can automatically
2373 2369 provide its contents either as a list (split on newlines) or as a
2374 2370 space-separated string. These are convenient, respectively, either
2375 2371 for sequential processing or to be passed to a shell command.
2376 2372
2377 2373 For example:
2378 2374
2379 2375 # Capture into variable a
2380 2376 In [9]: sc a=ls *py
2381 2377
2382 2378 # a is a string with embedded newlines
2383 2379 In [10]: a
2384 2380 Out[10]: 'setup.py\nwin32_manual_post_install.py'
2385 2381
2386 2382 # which can be seen as a list:
2387 2383 In [11]: a.l
2388 2384 Out[11]: ['setup.py', 'win32_manual_post_install.py']
2389 2385
2390 2386 # or as a whitespace-separated string:
2391 2387 In [12]: a.s
2392 2388 Out[12]: 'setup.py win32_manual_post_install.py'
2393 2389
2394 2390 # a.s is useful to pass as a single command line:
2395 2391 In [13]: !wc -l $a.s
2396 2392 146 setup.py
2397 2393 130 win32_manual_post_install.py
2398 2394 276 total
2399 2395
2400 2396 # while the list form is useful to loop over:
2401 2397 In [14]: for f in a.l:
2402 2398 ....: !wc -l $f
2403 2399 ....:
2404 2400 146 setup.py
2405 2401 130 win32_manual_post_install.py
2406 2402
2407 2403 Similiarly, the lists returned by the -l option are also special, in
2408 2404 the sense that you can equally invoke the .s attribute on them to
2409 2405 automatically get a whitespace-separated string from their contents:
2410 2406
2411 2407 In [1]: sc -l b=ls *py
2412 2408
2413 2409 In [2]: b
2414 2410 Out[2]: ['setup.py', 'win32_manual_post_install.py']
2415 2411
2416 2412 In [3]: b.s
2417 2413 Out[3]: 'setup.py win32_manual_post_install.py'
2418 2414
2419 2415 In summary, both the lists and strings used for ouptut capture have
2420 2416 the following special attributes:
2421 2417
2422 2418 .l (or .list) : value as list.
2423 2419 .n (or .nlstr): value as newline-separated string.
2424 2420 .s (or .spstr): value as space-separated string.
2425 2421 """
2426 2422
2427 2423 opts,args = self.parse_options(parameter_s,'lv')
2428 2424 # Try to get a variable name and command to run
2429 2425 try:
2430 2426 # the variable name must be obtained from the parse_options
2431 2427 # output, which uses shlex.split to strip options out.
2432 2428 var,_ = args.split('=',1)
2433 2429 var = var.strip()
2434 2430 # But the the command has to be extracted from the original input
2435 2431 # parameter_s, not on what parse_options returns, to avoid the
2436 2432 # quote stripping which shlex.split performs on it.
2437 2433 _,cmd = parameter_s.split('=',1)
2438 2434 except ValueError:
2439 2435 var,cmd = '',''
2440 2436 if not var:
2441 2437 error('you must specify a variable to assign the command to.')
2442 2438 return
2443 2439 # If all looks ok, proceed
2444 2440 out,err = self.shell.getoutputerror(cmd)
2445 2441 if err:
2446 2442 print >> Term.cerr,err
2447 2443 if opts.has_key('l'):
2448 2444 out = SList(out.split('\n'))
2449 2445 else:
2450 2446 out = LSString(out)
2451 2447 if opts.has_key('v'):
2452 2448 print '%s ==\n%s' % (var,pformat(out))
2453 2449 self.shell.user_ns.update({var:out})
2454 2450
2455 2451 def magic_sx(self, parameter_s=''):
2456 2452 """Shell execute - run a shell command and capture its output.
2457 2453
2458 2454 %sx command
2459 2455
2460 2456 IPython will run the given command using commands.getoutput(), and
2461 2457 return the result formatted as a list (split on '\\n'). Since the
2462 2458 output is _returned_, it will be stored in ipython's regular output
2463 2459 cache Out[N] and in the '_N' automatic variables.
2464 2460
2465 2461 Notes:
2466 2462
2467 2463 1) If an input line begins with '!!', then %sx is automatically
2468 2464 invoked. That is, while:
2469 2465 !ls
2470 2466 causes ipython to simply issue system('ls'), typing
2471 2467 !!ls
2472 2468 is a shorthand equivalent to:
2473 2469 %sx ls
2474 2470
2475 2471 2) %sx differs from %sc in that %sx automatically splits into a list,
2476 2472 like '%sc -l'. The reason for this is to make it as easy as possible
2477 2473 to process line-oriented shell output via further python commands.
2478 2474 %sc is meant to provide much finer control, but requires more
2479 2475 typing.
2480 2476
2481 2477 3) Just like %sc -l, this is a list with special attributes:
2482 2478
2483 2479 .l (or .list) : value as list.
2484 2480 .n (or .nlstr): value as newline-separated string.
2485 2481 .s (or .spstr): value as whitespace-separated string.
2486 2482
2487 2483 This is very useful when trying to use such lists as arguments to
2488 2484 system commands."""
2489 2485
2490 2486 if parameter_s:
2491 2487 out,err = self.shell.getoutputerror(parameter_s)
2492 2488 if err:
2493 2489 print >> Term.cerr,err
2494 2490 return SList(out.split('\n'))
2495 2491
2496 2492 def magic_bg(self, parameter_s=''):
2497 2493 """Run a job in the background, in a separate thread.
2498 2494
2499 2495 For example,
2500 2496
2501 2497 %bg myfunc(x,y,z=1)
2502 2498
2503 2499 will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the
2504 2500 execution starts, a message will be printed indicating the job
2505 2501 number. If your job number is 5, you can use
2506 2502
2507 2503 myvar = jobs.result(5) or myvar = jobs[5].result
2508 2504
2509 2505 to assign this result to variable 'myvar'.
2510 2506
2511 2507 IPython has a job manager, accessible via the 'jobs' object. You can
2512 2508 type jobs? to get more information about it, and use jobs.<TAB> to see
2513 2509 its attributes. All attributes not starting with an underscore are
2514 2510 meant for public use.
2515 2511
2516 2512 In particular, look at the jobs.new() method, which is used to create
2517 2513 new jobs. This magic %bg function is just a convenience wrapper
2518 2514 around jobs.new(), for expression-based jobs. If you want to create a
2519 2515 new job with an explicit function object and arguments, you must call
2520 2516 jobs.new() directly.
2521 2517
2522 2518 The jobs.new docstring also describes in detail several important
2523 2519 caveats associated with a thread-based model for background job
2524 2520 execution. Type jobs.new? for details.
2525 2521
2526 2522 You can check the status of all jobs with jobs.status().
2527 2523
2528 2524 The jobs variable is set by IPython into the Python builtin namespace.
2529 2525 If you ever declare a variable named 'jobs', you will shadow this
2530 2526 name. You can either delete your global jobs variable to regain
2531 2527 access to the job manager, or make a new name and assign it manually
2532 2528 to the manager (stored in IPython's namespace). For example, to
2533 2529 assign the job manager to the Jobs name, use:
2534 2530
2535 2531 Jobs = __builtins__.jobs"""
2536 2532
2537 2533 self.shell.jobs.new(parameter_s,self.shell.user_ns)
2538 2534
2539 2535 def magic_store(self, parameter_s=''):
2540 2536 """Lightweight persistence for python variables.
2541 2537
2542 2538 Example:
2543 2539
2544 2540 ville@badger[~]|1> A = ['hello',10,'world']\\
2545 2541 ville@badger[~]|2> %store A\\
2546 2542 ville@badger[~]|3> Exit
2547 2543
2548 2544 (IPython session is closed and started again...)
2549 2545
2550 2546 ville@badger:~$ ipython -p pysh\\
2551 2547 ville@badger[~]|1> print A
2552 2548
2553 2549 ['hello', 10, 'world']
2554 2550
2555 2551 Usage:
2556 2552
2557 2553 %store - Show list of all variables and their current values\\
2558 2554 %store <var> - Store the *current* value of the variable to disk\\
2559 2555 %store -d - Remove the variable and its value from storage\\
2560 2556 %store -r - Remove all variables from storage
2561 2557
2562 2558 It should be noted that if you change the value of a variable, you
2563 2559 need to %store it again if you want to persist the new value.
2564 2560
2565 2561 Note also that the variables will need to be pickleable; most basic
2566 2562 python types can be safely %stored.
2567 2563 """
2568 2564
2569 2565 opts,args = self.parse_options(parameter_s,'dr',mode='list')
2570 2566 # delete
2571 2567 if opts.has_key('d'):
2572 2568 try:
2573 2569 todel = args[0]
2574 2570 except IndexError:
2575 2571 error('You must provide the variable to forget')
2576 2572 else:
2577 2573 try:
2578 2574 del self.shell.persist['S:' + todel]
2579 2575 except:
2580 2576 error("Can't delete variable '%s'" % todel)
2581 2577 # reset
2582 2578 elif opts.has_key('r'):
2583 2579 for k in self.shell.persist.keys():
2584 2580 if k.startswith('S:'):
2585 2581 del self.shell.persist[k]
2586 2582
2587 2583 # run without arguments -> list variables & values
2588 2584 elif not args:
2589 2585 vars = [v[2:] for v in self.shell.persist.keys()
2590 2586 if v.startswith('S:')]
2591 2587 vars.sort()
2592 2588 if vars:
2593 2589 size = max(map(len,vars))
2594 2590 else:
2595 2591 size = 0
2596 2592
2597 2593 print 'Stored variables and their in-memory values:'
2598 2594 fmt = '%-'+str(size)+'s -> %s'
2599 2595 get = self.shell.user_ns.get
2600 2596 for var in vars:
2601 2597 # print 30 first characters from every var
2602 2598 print fmt % (var,repr(get(var,'<unavailable>'))[:50])
2603 2599
2604 2600 # default action - store the variable
2605 2601 else:
2606 2602 pickled = pickle.dumps(self.shell.user_ns[args[0] ])
2607 2603 self.shell.persist[ 'S:' + args[0] ] = pickled
2608 2604 print "Stored '%s' (%d bytes)" % (args[0], len(pickled))
2609 2605
2610 2606 def magic_bookmark(self, parameter_s=''):
2611 2607 """Manage IPython's bookmark system.
2612 2608
2613 2609 %bookmark <name> - set bookmark to current dir
2614 2610 %bookmark <name> <dir> - set bookmark to <dir>
2615 2611 %bookmark -l - list all bookmarks
2616 2612 %bookmark -d <name> - remove bookmark
2617 2613 %bookmark -r - remove all bookmarks
2618 2614
2619 2615 You can later on access a bookmarked folder with:
2620 2616 %cd -b <name>
2621 2617 or simply '%cd <name>' if there is no directory called <name> AND
2622 2618 there is such a bookmark defined.
2623 2619
2624 2620 Your bookmarks persist through IPython sessions, but they are
2625 2621 associated with each profile."""
2626 2622
2627 2623 opts,args = self.parse_options(parameter_s,'drl',mode='list')
2628 2624 if len(args) > 2:
2629 2625 error('You can only give at most two arguments')
2630 2626 return
2631 2627
2632 2628 bkms = self.shell.persist.get('bookmarks',{})
2633 2629
2634 2630 if opts.has_key('d'):
2635 2631 try:
2636 2632 todel = args[0]
2637 2633 except IndexError:
2638 2634 error('You must provide a bookmark to delete')
2639 2635 else:
2640 2636 try:
2641 2637 del bkms[todel]
2642 2638 except:
2643 2639 error("Can't delete bookmark '%s'" % todel)
2644 2640 elif opts.has_key('r'):
2645 2641 bkms = {}
2646 2642 elif opts.has_key('l'):
2647 2643 bks = bkms.keys()
2648 2644 bks.sort()
2649 2645 if bks:
2650 2646 size = max(map(len,bks))
2651 2647 else:
2652 2648 size = 0
2653 2649 fmt = '%-'+str(size)+'s -> %s'
2654 2650 print 'Current bookmarks:'
2655 2651 for bk in bks:
2656 2652 print fmt % (bk,bkms[bk])
2657 2653 else:
2658 2654 if not args:
2659 2655 error("You must specify the bookmark name")
2660 2656 elif len(args)==1:
2661 2657 bkms[args[0]] = os.getcwd()
2662 2658 elif len(args)==2:
2663 2659 bkms[args[0]] = args[1]
2664 2660 self.shell.persist['bookmarks'] = bkms
2665 2661
2666 2662 def magic_pycat(self, parameter_s=''):
2667 2663 """Show a syntax-highlighted file through a pager.
2668 2664
2669 2665 This magic is similar to the cat utility, but it will assume the file
2670 2666 to be Python source and will show it with syntax highlighting. """
2671 2667
2672 2668 filename = get_py_filename(parameter_s)
2673 2669 page(self.shell.colorize(file_read(filename)),
2674 2670 screen_lines=self.shell.rc.screen_length)
2675 2671
2676 2672 # end Magic
@@ -1,583 +1,583 b''
1 1 # -*- coding: utf-8 -*-
2 2 """
3 3 Classes for handling input/output prompts.
4 4
5 $Id: Prompts.py 966 2005-12-29 08:34:07Z fperez $"""
5 $Id: Prompts.py 975 2005-12-29 23:50:22Z fperez $"""
6 6
7 7 #*****************************************************************************
8 8 # Copyright (C) 2001-2004 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 from IPython import Release
15 15 __author__ = '%s <%s>' % Release.authors['Fernando']
16 16 __license__ = Release.license
17 17 __version__ = Release.version
18 18
19 19 #****************************************************************************
20 20 # Required modules
21 21 import __builtin__
22 22 import os
23 23 import socket
24 24 import sys
25 25 import time
26 26 from pprint import pprint,pformat
27 27
28 28 # IPython's own
29 from IPython.genutils import *
30 from IPython.Struct import Struct
31 from IPython.Magic import Macro
32 from IPython.Itpl import ItplNS
33 29 from IPython import ColorANSI
30 from IPython.Itpl import ItplNS
31 from IPython.Struct import Struct
32 from IPython.macro import Macro
33 from IPython.genutils import *
34 34
35 35 #****************************************************************************
36 36 #Color schemes for Prompts.
37 37
38 38 PromptColors = ColorANSI.ColorSchemeTable()
39 39 InputColors = ColorANSI.InputTermColors # just a shorthand
40 40 Colors = ColorANSI.TermColors # just a shorthand
41 41
42 42 PromptColors.add_scheme(ColorANSI.ColorScheme(
43 43 'NoColor',
44 44 in_prompt = InputColors.NoColor, # Input prompt
45 45 in_number = InputColors.NoColor, # Input prompt number
46 46 in_prompt2 = InputColors.NoColor, # Continuation prompt
47 47 in_normal = InputColors.NoColor, # color off (usu. Colors.Normal)
48 48
49 49 out_prompt = Colors.NoColor, # Output prompt
50 50 out_number = Colors.NoColor, # Output prompt number
51 51
52 52 normal = Colors.NoColor # color off (usu. Colors.Normal)
53 53 ))
54 54
55 55 # make some schemes as instances so we can copy them for modification easily:
56 56 __PColLinux = ColorANSI.ColorScheme(
57 57 'Linux',
58 58 in_prompt = InputColors.Green,
59 59 in_number = InputColors.LightGreen,
60 60 in_prompt2 = InputColors.Green,
61 61 in_normal = InputColors.Normal, # color off (usu. Colors.Normal)
62 62
63 63 out_prompt = Colors.Red,
64 64 out_number = Colors.LightRed,
65 65
66 66 normal = Colors.Normal
67 67 )
68 68 # Don't forget to enter it into the table!
69 69 PromptColors.add_scheme(__PColLinux)
70 70
71 71 # Slightly modified Linux for light backgrounds
72 72 __PColLightBG = __PColLinux.copy('LightBG')
73 73
74 74 __PColLightBG.colors.update(
75 75 in_prompt = InputColors.Blue,
76 76 in_number = InputColors.LightBlue,
77 77 in_prompt2 = InputColors.Blue
78 78 )
79 79 PromptColors.add_scheme(__PColLightBG)
80 80
81 81 del Colors,InputColors
82 82
83 83 #-----------------------------------------------------------------------------
84 84 def multiple_replace(dict, text):
85 85 """ Replace in 'text' all occurences of any key in the given
86 86 dictionary by its corresponding value. Returns the new string."""
87 87
88 88 # Function by Xavier Defrang, originally found at:
89 89 # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/81330
90 90
91 91 # Create a regular expression from the dictionary keys
92 92 regex = re.compile("(%s)" % "|".join(map(re.escape, dict.keys())))
93 93 # For each match, look-up corresponding value in dictionary
94 94 return regex.sub(lambda mo: dict[mo.string[mo.start():mo.end()]], text)
95 95
96 96 #-----------------------------------------------------------------------------
97 97 # Special characters that can be used in prompt templates, mainly bash-like
98 98
99 99 # If $HOME isn't defined (Windows), make it an absurd string so that it can
100 100 # never be expanded out into '~'. Basically anything which can never be a
101 101 # reasonable directory name will do, we just want the $HOME -> '~' operation
102 102 # to become a no-op. We pre-compute $HOME here so it's not done on every
103 103 # prompt call.
104 104
105 105 # FIXME:
106 106
107 107 # - This should be turned into a class which does proper namespace management,
108 108 # since the prompt specials need to be evaluated in a certain namespace.
109 109 # Currently it's just globals, which need to be managed manually by code
110 110 # below.
111 111
112 112 # - I also need to split up the color schemes from the prompt specials
113 113 # somehow. I don't have a clean design for that quite yet.
114 114
115 115 HOME = os.environ.get("HOME","//////:::::ZZZZZ,,,~~~")
116 116
117 117 # We precompute a few more strings here for the prompt_specials, which are
118 118 # fixed once ipython starts. This reduces the runtime overhead of computing
119 119 # prompt strings.
120 120 USER = os.environ.get("USER")
121 121 HOSTNAME = socket.gethostname()
122 122 HOSTNAME_SHORT = HOSTNAME.split(".")[0]
123 123 ROOT_SYMBOL = "$#"[os.name=='nt' or os.getuid()==0]
124 124
125 125 prompt_specials_color = {
126 126 # Prompt/history count
127 127 '%n' : '${self.col_num}' '${self.cache.prompt_count}' '${self.col_p}',
128 128 '\\#': '${self.col_num}' '${self.cache.prompt_count}' '${self.col_p}',
129 129 # Prompt/history count, with the actual digits replaced by dots. Used
130 130 # mainly in continuation prompts (prompt_in2)
131 131 '\\D': '${"."*len(str(self.cache.prompt_count))}',
132 132 # Current working directory
133 133 '\\w': '${os.getcwd()}',
134 134 # Current time
135 135 '\\t' : '${time.strftime("%H:%M:%S")}',
136 136 # Basename of current working directory.
137 137 # (use os.sep to make this portable across OSes)
138 138 '\\W' : '${os.getcwd().split("%s")[-1]}' % os.sep,
139 139 # These X<N> are an extension to the normal bash prompts. They return
140 140 # N terms of the path, after replacing $HOME with '~'
141 141 '\\X0': '${os.getcwd().replace("%s","~")}' % HOME,
142 142 '\\X1': '${self.cwd_filt(1)}',
143 143 '\\X2': '${self.cwd_filt(2)}',
144 144 '\\X3': '${self.cwd_filt(3)}',
145 145 '\\X4': '${self.cwd_filt(4)}',
146 146 '\\X5': '${self.cwd_filt(5)}',
147 147 # Y<N> are similar to X<N>, but they show '~' if it's the directory
148 148 # N+1 in the list. Somewhat like %cN in tcsh.
149 149 '\\Y0': '${self.cwd_filt2(0)}',
150 150 '\\Y1': '${self.cwd_filt2(1)}',
151 151 '\\Y2': '${self.cwd_filt2(2)}',
152 152 '\\Y3': '${self.cwd_filt2(3)}',
153 153 '\\Y4': '${self.cwd_filt2(4)}',
154 154 '\\Y5': '${self.cwd_filt2(5)}',
155 155 # Hostname up to first .
156 156 '\\h': HOSTNAME_SHORT,
157 157 # Full hostname
158 158 '\\H': HOSTNAME,
159 159 # Username of current user
160 160 '\\u': USER,
161 161 # Escaped '\'
162 162 '\\\\': '\\',
163 163 # Newline
164 164 '\\n': '\n',
165 165 # Carriage return
166 166 '\\r': '\r',
167 167 # Release version
168 168 '\\v': __version__,
169 169 # Root symbol ($ or #)
170 170 '\\$': ROOT_SYMBOL,
171 171 }
172 172
173 173 # A copy of the prompt_specials dictionary but with all color escapes removed,
174 174 # so we can correctly compute the prompt length for the auto_rewrite method.
175 175 prompt_specials_nocolor = prompt_specials_color.copy()
176 176 prompt_specials_nocolor['%n'] = '${self.cache.prompt_count}'
177 177 prompt_specials_nocolor['\\#'] = '${self.cache.prompt_count}'
178 178
179 179 # Add in all the InputTermColors color escapes as valid prompt characters.
180 180 # They all get added as \\C_COLORNAME, so that we don't have any conflicts
181 181 # with a color name which may begin with a letter used by any other of the
182 182 # allowed specials. This of course means that \\C will never be allowed for
183 183 # anything else.
184 184 input_colors = ColorANSI.InputTermColors
185 185 for _color in dir(input_colors):
186 186 if _color[0] != '_':
187 187 c_name = '\\C_'+_color
188 188 prompt_specials_color[c_name] = getattr(input_colors,_color)
189 189 prompt_specials_nocolor[c_name] = ''
190 190
191 191 # we default to no color for safety. Note that prompt_specials is a global
192 192 # variable used by all prompt objects.
193 193 prompt_specials = prompt_specials_nocolor
194 194
195 195 #-----------------------------------------------------------------------------
196 196 def str_safe(arg):
197 197 """Convert to a string, without ever raising an exception.
198 198
199 199 If str(arg) fails, <ERROR: ... > is returned, where ... is the exception
200 200 error message."""
201 201
202 202 try:
203 203 out = str(arg)
204 204 except UnicodeError:
205 205 try:
206 206 out = arg.encode('utf_8','replace')
207 207 except Exception,msg:
208 208 # let's keep this little duplication here, so that the most common
209 209 # case doesn't suffer from a double try wrapping.
210 210 out = '<ERROR: %s>' % msg
211 211 except Exception,msg:
212 212 out = '<ERROR: %s>' % msg
213 213 return out
214 214
215 215 class BasePrompt:
216 216 """Interactive prompt similar to Mathematica's."""
217 217 def __init__(self,cache,sep,prompt,pad_left=False):
218 218
219 219 # Hack: we access information about the primary prompt through the
220 220 # cache argument. We need this, because we want the secondary prompt
221 221 # to be aligned with the primary one. Color table info is also shared
222 222 # by all prompt classes through the cache. Nice OO spaghetti code!
223 223 self.cache = cache
224 224 self.sep = sep
225 225
226 226 # regexp to count the number of spaces at the end of a prompt
227 227 # expression, useful for prompt auto-rewriting
228 228 self.rspace = re.compile(r'(\s*)$')
229 229 # Flag to left-pad prompt strings to match the length of the primary
230 230 # prompt
231 231 self.pad_left = pad_left
232 232 # Set template to create each actual prompt (where numbers change)
233 233 self.p_template = prompt
234 234 self.set_p_str()
235 235
236 236 def set_p_str(self):
237 237 """ Set the interpolating prompt strings.
238 238
239 239 This must be called every time the color settings change, because the
240 240 prompt_specials global may have changed."""
241 241
242 242 import os,time # needed in locals for prompt string handling
243 243 loc = locals()
244 244 self.p_str = ItplNS('%s%s%s' %
245 245 ('${self.sep}${self.col_p}',
246 246 multiple_replace(prompt_specials, self.p_template),
247 247 '${self.col_norm}'),self.cache.user_ns,loc)
248 248
249 249 self.p_str_nocolor = ItplNS(multiple_replace(prompt_specials_nocolor,
250 250 self.p_template),
251 251 self.cache.user_ns,loc)
252 252
253 253 def write(self,msg): # dbg
254 254 sys.stdout.write(msg)
255 255 return ''
256 256
257 257 def __str__(self):
258 258 """Return a string form of the prompt.
259 259
260 260 This for is useful for continuation and output prompts, since it is
261 261 left-padded to match lengths with the primary one (if the
262 262 self.pad_left attribute is set)."""
263 263
264 264 out_str = str_safe(self.p_str)
265 265 if self.pad_left:
266 266 # We must find the amount of padding required to match lengths,
267 267 # taking the color escapes (which are invisible on-screen) into
268 268 # account.
269 269 esc_pad = len(out_str) - len(str_safe(self.p_str_nocolor))
270 270 format = '%%%ss' % (len(str(self.cache.last_prompt))+esc_pad)
271 271 return format % out_str
272 272 else:
273 273 return out_str
274 274
275 275 # these path filters are put in as methods so that we can control the
276 276 # namespace where the prompt strings get evaluated
277 277 def cwd_filt(self,depth):
278 278 """Return the last depth elements of the current working directory.
279 279
280 280 $HOME is always replaced with '~'.
281 281 If depth==0, the full path is returned."""
282 282
283 283 cwd = os.getcwd().replace(HOME,"~")
284 284 out = os.sep.join(cwd.split(os.sep)[-depth:])
285 285 if out:
286 286 return out
287 287 else:
288 288 return os.sep
289 289
290 290 def cwd_filt2(self,depth):
291 291 """Return the last depth elements of the current working directory.
292 292
293 293 $HOME is always replaced with '~'.
294 294 If depth==0, the full path is returned."""
295 295
296 296 cwd = os.getcwd().replace(HOME,"~").split(os.sep)
297 297 if '~' in cwd and len(cwd) == depth+1:
298 298 depth += 1
299 299 out = os.sep.join(cwd[-depth:])
300 300 if out:
301 301 return out
302 302 else:
303 303 return os.sep
304 304
305 305 class Prompt1(BasePrompt):
306 306 """Input interactive prompt similar to Mathematica's."""
307 307
308 308 def __init__(self,cache,sep='\n',prompt='In [\\#]: ',pad_left=True):
309 309 BasePrompt.__init__(self,cache,sep,prompt,pad_left)
310 310
311 311 def set_colors(self):
312 312 self.set_p_str()
313 313 Colors = self.cache.color_table.active_colors # shorthand
314 314 self.col_p = Colors.in_prompt
315 315 self.col_num = Colors.in_number
316 316 self.col_norm = Colors.in_normal
317 317 # We need a non-input version of these escapes for the '--->'
318 318 # auto-call prompts used in the auto_rewrite() method.
319 319 self.col_p_ni = self.col_p.replace('\001','').replace('\002','')
320 320 self.col_norm_ni = Colors.normal
321 321
322 322 def __str__(self):
323 323 self.cache.prompt_count += 1
324 324 self.cache.last_prompt = str_safe(self.p_str_nocolor).split('\n')[-1]
325 325 return str_safe(self.p_str)
326 326
327 327 def auto_rewrite(self):
328 328 """Print a string of the form '--->' which lines up with the previous
329 329 input string. Useful for systems which re-write the user input when
330 330 handling automatically special syntaxes."""
331 331
332 332 curr = str(self.cache.last_prompt)
333 333 nrspaces = len(self.rspace.search(curr).group())
334 334 return '%s%s>%s%s' % (self.col_p_ni,'-'*(len(curr)-nrspaces-1),
335 335 ' '*nrspaces,self.col_norm_ni)
336 336
337 337 class PromptOut(BasePrompt):
338 338 """Output interactive prompt similar to Mathematica's."""
339 339
340 340 def __init__(self,cache,sep='',prompt='Out[\\#]: ',pad_left=True):
341 341 BasePrompt.__init__(self,cache,sep,prompt,pad_left)
342 342 if not self.p_template:
343 343 self.__str__ = lambda: ''
344 344
345 345 def set_colors(self):
346 346 self.set_p_str()
347 347 Colors = self.cache.color_table.active_colors # shorthand
348 348 self.col_p = Colors.out_prompt
349 349 self.col_num = Colors.out_number
350 350 self.col_norm = Colors.normal
351 351
352 352 class Prompt2(BasePrompt):
353 353 """Interactive continuation prompt."""
354 354
355 355 def __init__(self,cache,prompt=' .\\D.: ',pad_left=True):
356 356 self.cache = cache
357 357 self.p_template = prompt
358 358 self.pad_left = pad_left
359 359 self.set_p_str()
360 360
361 361 def set_p_str(self):
362 362 import os,time # needed in locals for prompt string handling
363 363 loc = locals()
364 364 self.p_str = ItplNS('%s%s%s' %
365 365 ('${self.col_p2}',
366 366 multiple_replace(prompt_specials, self.p_template),
367 367 '$self.col_norm'),
368 368 self.cache.user_ns,loc)
369 369 self.p_str_nocolor = ItplNS(multiple_replace(prompt_specials_nocolor,
370 370 self.p_template),
371 371 self.cache.user_ns,loc)
372 372
373 373 def set_colors(self):
374 374 self.set_p_str()
375 375 Colors = self.cache.color_table.active_colors
376 376 self.col_p2 = Colors.in_prompt2
377 377 self.col_norm = Colors.in_normal
378 378 # FIXME (2004-06-16) HACK: prevent crashes for users who haven't
379 379 # updated their prompt_in2 definitions. Remove eventually.
380 380 self.col_p = Colors.out_prompt
381 381 self.col_num = Colors.out_number
382 382
383 383 #-----------------------------------------------------------------------------
384 384 class CachedOutput:
385 385 """Class for printing output from calculations while keeping a cache of
386 386 reults. It dynamically creates global variables prefixed with _ which
387 387 contain these results.
388 388
389 389 Meant to be used as a sys.displayhook replacement, providing numbered
390 390 prompts and cache services.
391 391
392 392 Initialize with initial and final values for cache counter (this defines
393 393 the maximum size of the cache."""
394 394
395 395 def __init__(self,shell,cache_size,Pprint,
396 396 colors='NoColor',input_sep='\n',
397 397 output_sep='\n',output_sep2='',
398 398 ps1 = None, ps2 = None,ps_out = None,pad_left=True):
399 399
400 400 cache_size_min = 20
401 401 if cache_size <= 0:
402 402 self.do_full_cache = 0
403 403 cache_size = 0
404 404 elif cache_size < cache_size_min:
405 405 self.do_full_cache = 0
406 406 cache_size = 0
407 407 warn('caching was disabled (min value for cache size is %s).' %
408 408 cache_size_min,level=3)
409 409 else:
410 410 self.do_full_cache = 1
411 411
412 412 self.cache_size = cache_size
413 413 self.input_sep = input_sep
414 414
415 415 # we need a reference to the user-level namespace
416 416 self.shell = shell
417 417 self.user_ns = shell.user_ns
418 418 # and to the user's input
419 419 self.input_hist = shell.input_hist
420 420 # and to the user's logger, for logging output
421 421 self.logger = shell.logger
422 422
423 423 # Set input prompt strings and colors
424 424 if cache_size == 0:
425 425 if ps1.find('%n') > -1 or ps1.find('\\#') > -1: ps1 = '>>> '
426 426 if ps2.find('%n') > -1 or ps2.find('\\#') > -1: ps2 = '... '
427 427 self.ps1_str = self._set_prompt_str(ps1,'In [\\#]: ','>>> ')
428 428 self.ps2_str = self._set_prompt_str(ps2,' .\\D.: ','... ')
429 429 self.ps_out_str = self._set_prompt_str(ps_out,'Out[\\#]: ','')
430 430
431 431 self.color_table = PromptColors
432 432 self.prompt1 = Prompt1(self,sep=input_sep,prompt=self.ps1_str,
433 433 pad_left=pad_left)
434 434 self.prompt2 = Prompt2(self,prompt=self.ps2_str,pad_left=pad_left)
435 435 self.prompt_out = PromptOut(self,sep='',prompt=self.ps_out_str,
436 436 pad_left=pad_left)
437 437 self.set_colors(colors)
438 438
439 439 # other more normal stuff
440 440 # b/c each call to the In[] prompt raises it by 1, even the first.
441 441 self.prompt_count = 0
442 442 self.cache_count = 1
443 443 # Store the last prompt string each time, we need it for aligning
444 444 # continuation and auto-rewrite prompts
445 445 self.last_prompt = ''
446 446 self.entries = [None] # output counter starts at 1 for the user
447 447 self.Pprint = Pprint
448 448 self.output_sep = output_sep
449 449 self.output_sep2 = output_sep2
450 450 self._,self.__,self.___ = '','',''
451 451 self.pprint_types = map(type,[(),[],{}])
452 452
453 453 # these are deliberately global:
454 454 to_user_ns = {'_':self._,'__':self.__,'___':self.___}
455 455 self.user_ns.update(to_user_ns)
456 456
457 457 def _set_prompt_str(self,p_str,cache_def,no_cache_def):
458 458 if p_str is None:
459 459 if self.do_full_cache:
460 460 return cache_def
461 461 else:
462 462 return no_cache_def
463 463 else:
464 464 return p_str
465 465
466 466 def set_colors(self,colors):
467 467 """Set the active color scheme and configure colors for the three
468 468 prompt subsystems."""
469 469
470 470 # FIXME: the prompt_specials global should be gobbled inside this
471 471 # class instead. Do it when cleaning up the whole 3-prompt system.
472 472 global prompt_specials
473 473 if colors.lower()=='nocolor':
474 474 prompt_specials = prompt_specials_nocolor
475 475 else:
476 476 prompt_specials = prompt_specials_color
477 477
478 478 self.color_table.set_active_scheme(colors)
479 479 self.prompt1.set_colors()
480 480 self.prompt2.set_colors()
481 481 self.prompt_out.set_colors()
482 482
483 483 def __call__(self,arg=None):
484 484 """Printing with history cache management.
485 485
486 486 This is invoked everytime the interpreter needs to print, and is
487 487 activated by setting the variable sys.displayhook to it."""
488 488
489 489 # If something injected a '_' variable in __builtin__, delete
490 490 # ipython's automatic one so we don't clobber that. gettext() in
491 491 # particular uses _, so we need to stay away from it.
492 492 if '_' in __builtin__.__dict__:
493 493 try:
494 494 del self.user_ns['_']
495 495 except KeyError:
496 496 pass
497 497 if arg is not None:
498 498 cout_write = Term.cout.write # fast lookup
499 499 # first handle the cache and counters
500 500 # but avoid recursive reference when displaying _oh/Out
501 501 if arg is not self.user_ns['_oh']:
502 502 self.update(arg)
503 503 # do not print output if input ends in ';'
504 504 if self.input_hist[self.prompt_count].endswith(';\n'):
505 505 return
506 506 # don't use print, puts an extra space
507 507 cout_write(self.output_sep)
508 508 if self.do_full_cache:
509 509 cout_write(str(self.prompt_out))
510 510
511 511 if isinstance(arg,Macro):
512 512 print 'Executing Macro...'
513 513 # in case the macro takes a long time to execute
514 514 Term.cout.flush()
515 515 self.shell.runlines(arg.value)
516 516 return None
517 517
518 518 # and now call a possibly user-defined print mechanism
519 519 self.display(arg)
520 520 if self.logger.log_output:
521 521 self.logger.log_write(repr(arg),'output')
522 522 cout_write(self.output_sep2)
523 523 Term.cout.flush()
524 524
525 525 def _display(self,arg):
526 526 """Default printer method, uses pprint.
527 527
528 528 This can be over-ridden by the users to implement special formatting
529 529 of certain types of output."""
530 530
531 531 if self.Pprint:
532 532 out = pformat(arg)
533 533 if '\n' in out:
534 534 # So that multi-line strings line up with the left column of
535 535 # the screen, instead of having the output prompt mess up
536 536 # their first line.
537 537 Term.cout.write('\n')
538 538 print >>Term.cout, out
539 539 else:
540 540 print >>Term.cout, arg
541 541
542 542 # Assign the default display method:
543 543 display = _display
544 544
545 545 def update(self,arg):
546 546 #print '***cache_count', self.cache_count # dbg
547 547 if self.cache_count >= self.cache_size and self.do_full_cache:
548 548 self.flush()
549 549 # Don't overwrite '_' and friends if '_' is in __builtin__ (otherwise
550 550 # we cause buggy behavior for things like gettext).
551 551 if '_' not in __builtin__.__dict__:
552 552 self.___ = self.__
553 553 self.__ = self._
554 554 self._ = arg
555 555 self.user_ns.update({'_':self._,'__':self.__,'___':self.___})
556 556
557 557 # hackish access to top-level namespace to create _1,_2... dynamically
558 558 to_main = {}
559 559 if self.do_full_cache:
560 560 self.cache_count += 1
561 561 self.entries.append(arg)
562 562 new_result = '_'+`self.prompt_count`
563 563 to_main[new_result] = self.entries[-1]
564 564 self.user_ns.update(to_main)
565 565 self.user_ns['_oh'][self.prompt_count] = arg
566 566
567 567 def flush(self):
568 568 if not self.do_full_cache:
569 569 raise ValueError,"You shouldn't have reached the cache flush "\
570 570 "if full caching is not enabled!"
571 571 warn('Output cache limit (currently '+\
572 572 `self.cache_count`+' entries) hit.\n'
573 573 'Flushing cache and resetting history counter...\n'
574 574 'The only history variables available will be _,__,___ and _1\n'
575 575 'with the current result.')
576 576 # delete auto-generated vars from global namespace
577 577 for n in range(1,self.prompt_count + 1):
578 578 key = '_'+`n`
579 579 try:
580 580 del self.user_ns[key]
581 581 except: pass
582 582 self.prompt_count = 1
583 583 self.cache_count = 1
@@ -1,2051 +1,2056 b''
1 1 # -*- coding: utf-8 -*-
2 2 """
3 3 IPython -- An enhanced Interactive Python
4 4
5 5 Requires Python 2.1 or newer.
6 6
7 7 This file contains all the classes and helper functions specific to IPython.
8 8
9 $Id: iplib.py 968 2005-12-29 17:15:38Z fperez $
9 $Id: iplib.py 975 2005-12-29 23:50:22Z fperez $
10 10 """
11 11
12 12 #*****************************************************************************
13 13 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
14 14 # Copyright (C) 2001-2005 Fernando Perez. <fperez@colorado.edu>
15 15 #
16 16 # Distributed under the terms of the BSD License. The full license is in
17 17 # the file COPYING, distributed as part of this software.
18 18 #
19 19 # Note: this code originally subclassed code.InteractiveConsole from the
20 20 # Python standard library. Over time, all of that class has been copied
21 21 # verbatim here for modifications which could not be accomplished by
22 22 # subclassing. At this point, there are no dependencies at all on the code
23 23 # module anymore (it is not even imported). The Python License (sec. 2)
24 24 # allows for this, but it's always nice to acknowledge credit where credit is
25 25 # due.
26 26 #*****************************************************************************
27 27
28 28 #****************************************************************************
29 29 # Modules and globals
30 30
31 31 from __future__ import generators # for 2.2 backwards-compatibility
32 32
33 33 from IPython import Release
34 34 __author__ = '%s <%s>\n%s <%s>' % \
35 35 ( Release.authors['Janko'] + Release.authors['Fernando'] )
36 36 __license__ = Release.license
37 37 __version__ = Release.version
38 38
39 39 # Python standard modules
40 40 import __main__
41 41 import __builtin__
42 42 import StringIO
43 43 import bdb
44 44 import cPickle as pickle
45 45 import codeop
46 46 import exceptions
47 47 import glob
48 48 import inspect
49 49 import keyword
50 50 import new
51 51 import os
52 52 import pdb
53 53 import pydoc
54 54 import re
55 55 import shutil
56 56 import string
57 57 import sys
58 58 import traceback
59 59 import types
60 60
61 61 from pprint import pprint, pformat
62 62
63 63 # IPython's own modules
64 64 import IPython
65 65 from IPython import OInspect,PyColorize,ultraTB
66 66 from IPython.ColorANSI import ColorScheme,ColorSchemeTable # too long names
67 67 from IPython.FakeModule import FakeModule
68 68 from IPython.Itpl import Itpl,itpl,printpl,ItplNS,itplns
69 69 from IPython.Logger import Logger
70 70 from IPython.Magic import Magic
71 71 from IPython.Prompts import CachedOutput
72 72 from IPython.Struct import Struct
73 73 from IPython.background_jobs import BackgroundJobManager
74 74 from IPython.usage import cmd_line_usage,interactive_usage
75 75 from IPython.genutils import *
76 76
77 77 # store the builtin raw_input globally, and use this always, in case user code
78 78 # overwrites it (like wx.py.PyShell does)
79 79 raw_input_original = raw_input
80 80
81 # compiled regexps for autoindent management
82 ini_spaces_re = re.compile(r'^(\s+)')
83 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
84
81 85 #****************************************************************************
82 86 # Some utility function definitions
83 87
84 88 def softspace(file, newvalue):
85 89 """Copied from code.py, to remove the dependency"""
86 90 oldvalue = 0
87 91 try:
88 92 oldvalue = file.softspace
89 93 except AttributeError:
90 94 pass
91 95 try:
92 96 file.softspace = newvalue
93 97 except (AttributeError, TypeError):
94 98 # "attribute-less object" or "read-only attributes"
95 99 pass
96 100 return oldvalue
97 101
98 102 #****************************************************************************
99 103 # These special functions get installed in the builtin namespace, to provide
100 104 # programmatic (pure python) access to magics and aliases. This is important
101 105 # for logging, user scripting, and more.
102 106
103 107 def ipmagic(arg_s):
104 108 """Call a magic function by name.
105 109
106 110 Input: a string containing the name of the magic function to call and any
107 111 additional arguments to be passed to the magic.
108 112
109 113 ipmagic('name -opt foo bar') is equivalent to typing at the ipython
110 114 prompt:
111 115
112 116 In[1]: %name -opt foo bar
113 117
114 118 To call a magic without arguments, simply use ipmagic('name').
115 119
116 120 This provides a proper Python function to call IPython's magics in any
117 121 valid Python code you can type at the interpreter, including loops and
118 122 compound statements. It is added by IPython to the Python builtin
119 123 namespace upon initialization."""
120 124
121 125 args = arg_s.split(' ',1)
122 126 magic_name = args[0]
123 127 if magic_name.startswith(__IPYTHON__.ESC_MAGIC):
124 128 magic_name = magic_name[1:]
125 129 try:
126 130 magic_args = args[1]
127 131 except IndexError:
128 132 magic_args = ''
129 133 fn = getattr(__IPYTHON__,'magic_'+magic_name,None)
130 134 if fn is None:
131 135 error("Magic function `%s` not found." % magic_name)
132 136 else:
133 137 magic_args = __IPYTHON__.var_expand(magic_args)
134 138 return fn(magic_args)
135 139
136 140 def ipalias(arg_s):
137 141 """Call an alias by name.
138 142
139 143 Input: a string containing the name of the alias to call and any
140 144 additional arguments to be passed to the magic.
141 145
142 146 ipalias('name -opt foo bar') is equivalent to typing at the ipython
143 147 prompt:
144 148
145 149 In[1]: name -opt foo bar
146 150
147 151 To call an alias without arguments, simply use ipalias('name').
148 152
149 153 This provides a proper Python function to call IPython's aliases in any
150 154 valid Python code you can type at the interpreter, including loops and
151 155 compound statements. It is added by IPython to the Python builtin
152 156 namespace upon initialization."""
153 157
154 158 args = arg_s.split(' ',1)
155 159 alias_name = args[0]
156 160 try:
157 161 alias_args = args[1]
158 162 except IndexError:
159 163 alias_args = ''
160 164 if alias_name in __IPYTHON__.alias_table:
161 165 __IPYTHON__.call_alias(alias_name,alias_args)
162 166 else:
163 167 error("Alias `%s` not found." % alias_name)
164 168
165 169 #****************************************************************************
166 170 # Local use exceptions
167 171 class SpaceInInput(exceptions.Exception): pass
168 172
169 173 #****************************************************************************
170 174 # Local use classes
171 175 class Bunch: pass
172 176
173 177 class InputList(list):
174 178 """Class to store user input.
175 179
176 180 It's basically a list, but slices return a string instead of a list, thus
177 181 allowing things like (assuming 'In' is an instance):
178 182
179 183 exec In[4:7]
180 184
181 185 or
182 186
183 187 exec In[5:9] + In[14] + In[21:25]"""
184 188
185 189 def __getslice__(self,i,j):
186 190 return ''.join(list.__getslice__(self,i,j))
187 191
188 192 class SyntaxTB(ultraTB.ListTB):
189 193 """Extension which holds some state: the last exception value"""
190 194
191 195 def __init__(self,color_scheme = 'NoColor'):
192 196 ultraTB.ListTB.__init__(self,color_scheme)
193 197 self.last_syntax_error = None
194 198
195 199 def __call__(self, etype, value, elist):
196 200 self.last_syntax_error = value
197 201 ultraTB.ListTB.__call__(self,etype,value,elist)
198 202
199 203 def clear_err_state(self):
200 204 """Return the current error state and clear it"""
201 205 e = self.last_syntax_error
202 206 self.last_syntax_error = None
203 207 return e
204 208
205 209 #****************************************************************************
206 210 # Main IPython class
207 211
208 212 # FIXME: the Magic class is a mixin for now, and will unfortunately remain so
209 213 # until a full rewrite is made. I've cleaned all cross-class uses of
210 214 # attributes and methods, but too much user code out there relies on the
211 215 # equlity %foo == __IP.magic_foo, so I can't actually remove the mixin usage.
212 216 #
213 217 # But at least now, all the pieces have been separated and we could, in
214 218 # principle, stop using the mixin. This will ease the transition to the
215 219 # chainsaw branch.
216 220
217 221 # For reference, the following is the list of 'self.foo' uses in the Magic
218 222 # class as of 2005-12-28. These are names we CAN'T use in the main ipython
219 223 # class, to prevent clashes.
220 224
221 225 # ['self.__class__', 'self.__dict__', 'self._inspect', 'self._ofind',
222 226 # 'self.arg_err', 'self.extract_input', 'self.format_', 'self.lsmagic',
223 227 # 'self.magic_', 'self.options_table', 'self.parse', 'self.shell',
224 228 # 'self.value']
225 229
226 230 class InteractiveShell(Magic):
227 231 """An enhanced console for Python."""
228 232
229 233 # class attribute to indicate whether the class supports threads or not.
230 234 # Subclasses with thread support should override this as needed.
231 235 isthreaded = False
232 236
233 237 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
234 238 user_ns = None,user_global_ns=None,banner2='',
235 239 custom_exceptions=((),None),embedded=False):
236 240
237 241 # some minimal strict typechecks. For some core data structures, I
238 242 # want actual basic python types, not just anything that looks like
239 243 # one. This is especially true for namespaces.
240 244 for ns in (user_ns,user_global_ns):
241 245 if ns is not None and type(ns) != types.DictType:
242 246 raise TypeError,'namespace must be a dictionary'
243 247
244 248 # Put a reference to self in builtins so that any form of embedded or
245 249 # imported code can test for being inside IPython.
246 250 __builtin__.__IPYTHON__ = self
247 251
248 252 # And load into builtins ipmagic/ipalias as well
249 253 __builtin__.ipmagic = ipmagic
250 254 __builtin__.ipalias = ipalias
251 255
252 256 # Add to __builtin__ other parts of IPython's public API
253 257 __builtin__.ip_set_hook = self.set_hook
254 258
255 259 # Keep in the builtins a flag for when IPython is active. We set it
256 260 # with setdefault so that multiple nested IPythons don't clobber one
257 261 # another. Each will increase its value by one upon being activated,
258 262 # which also gives us a way to determine the nesting level.
259 263 __builtin__.__dict__.setdefault('__IPYTHON__active',0)
260 264
261 265 # Do the intuitively correct thing for quit/exit: we remove the
262 266 # builtins if they exist, and our own prefilter routine will handle
263 267 # these special cases
264 268 try:
265 269 del __builtin__.exit, __builtin__.quit
266 270 except AttributeError:
267 271 pass
268 272
269 273 # Store the actual shell's name
270 274 self.name = name
271 275
272 276 # We need to know whether the instance is meant for embedding, since
273 277 # global/local namespaces need to be handled differently in that case
274 278 self.embedded = embedded
275 279
276 280 # command compiler
277 281 self.compile = codeop.CommandCompiler()
278 282
279 283 # User input buffer
280 284 self.buffer = []
281 285
282 286 # Default name given in compilation of code
283 287 self.filename = '<ipython console>'
284 288
285 289 # Create the namespace where the user will operate. user_ns is
286 290 # normally the only one used, and it is passed to the exec calls as
287 291 # the locals argument. But we do carry a user_global_ns namespace
288 292 # given as the exec 'globals' argument, This is useful in embedding
289 293 # situations where the ipython shell opens in a context where the
290 294 # distinction between locals and globals is meaningful.
291 295
292 296 # FIXME. For some strange reason, __builtins__ is showing up at user
293 297 # level as a dict instead of a module. This is a manual fix, but I
294 298 # should really track down where the problem is coming from. Alex
295 299 # Schmolck reported this problem first.
296 300
297 301 # A useful post by Alex Martelli on this topic:
298 302 # Re: inconsistent value from __builtins__
299 303 # Von: Alex Martelli <aleaxit@yahoo.com>
300 304 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
301 305 # Gruppen: comp.lang.python
302 306
303 307 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
304 308 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
305 309 # > <type 'dict'>
306 310 # > >>> print type(__builtins__)
307 311 # > <type 'module'>
308 312 # > Is this difference in return value intentional?
309 313
310 314 # Well, it's documented that '__builtins__' can be either a dictionary
311 315 # or a module, and it's been that way for a long time. Whether it's
312 316 # intentional (or sensible), I don't know. In any case, the idea is
313 317 # that if you need to access the built-in namespace directly, you
314 318 # should start with "import __builtin__" (note, no 's') which will
315 319 # definitely give you a module. Yeah, it's somewhat confusing:-(.
316 320
317 321 if user_ns is None:
318 322 # Set __name__ to __main__ to better match the behavior of the
319 323 # normal interpreter.
320 324 user_ns = {'__name__' :'__main__',
321 325 '__builtins__' : __builtin__,
322 326 }
323 327
324 328 if user_global_ns is None:
325 329 user_global_ns = {}
326 330
327 331 # Assign namespaces
328 332 # This is the namespace where all normal user variables live
329 333 self.user_ns = user_ns
330 334 # Embedded instances require a separate namespace for globals.
331 335 # Normally this one is unused by non-embedded instances.
332 336 self.user_global_ns = user_global_ns
333 337 # A namespace to keep track of internal data structures to prevent
334 338 # them from cluttering user-visible stuff. Will be updated later
335 339 self.internal_ns = {}
336 340
337 341 # Namespace of system aliases. Each entry in the alias
338 342 # table must be a 2-tuple of the form (N,name), where N is the number
339 343 # of positional arguments of the alias.
340 344 self.alias_table = {}
341 345
342 346 # A table holding all the namespaces IPython deals with, so that
343 347 # introspection facilities can search easily.
344 348 self.ns_table = {'user':user_ns,
345 349 'user_global':user_global_ns,
346 350 'alias':self.alias_table,
347 351 'internal':self.internal_ns,
348 352 'builtin':__builtin__.__dict__
349 353 }
350 354
351 355 # The user namespace MUST have a pointer to the shell itself.
352 356 self.user_ns[name] = self
353 357
354 358 # We need to insert into sys.modules something that looks like a
355 359 # module but which accesses the IPython namespace, for shelve and
356 360 # pickle to work interactively. Normally they rely on getting
357 361 # everything out of __main__, but for embedding purposes each IPython
358 362 # instance has its own private namespace, so we can't go shoving
359 363 # everything into __main__.
360 364
361 365 # note, however, that we should only do this for non-embedded
362 366 # ipythons, which really mimic the __main__.__dict__ with their own
363 367 # namespace. Embedded instances, on the other hand, should not do
364 368 # this because they need to manage the user local/global namespaces
365 369 # only, but they live within a 'normal' __main__ (meaning, they
366 370 # shouldn't overtake the execution environment of the script they're
367 371 # embedded in).
368 372
369 373 if not embedded:
370 374 try:
371 375 main_name = self.user_ns['__name__']
372 376 except KeyError:
373 377 raise KeyError,'user_ns dictionary MUST have a "__name__" key'
374 378 else:
375 379 #print "pickle hack in place" # dbg
376 380 sys.modules[main_name] = FakeModule(self.user_ns)
377 381
378 382 # List of input with multi-line handling.
379 383 # Fill its zero entry, user counter starts at 1
380 384 self.input_hist = InputList(['\n'])
381 385
382 386 # list of visited directories
383 387 try:
384 388 self.dir_hist = [os.getcwd()]
385 389 except IOError, e:
386 390 self.dir_hist = []
387 391
388 392 # dict of output history
389 393 self.output_hist = {}
390 394
391 395 # dict of things NOT to alias (keywords, builtins and some magics)
392 396 no_alias = {}
393 397 no_alias_magics = ['cd','popd','pushd','dhist','alias','unalias']
394 398 for key in keyword.kwlist + no_alias_magics:
395 399 no_alias[key] = 1
396 400 no_alias.update(__builtin__.__dict__)
397 401 self.no_alias = no_alias
398 402
399 403 # make global variables for user access to these
400 404 self.user_ns['_ih'] = self.input_hist
401 405 self.user_ns['_oh'] = self.output_hist
402 406 self.user_ns['_dh'] = self.dir_hist
403 407
404 408 # user aliases to input and output histories
405 409 self.user_ns['In'] = self.input_hist
406 410 self.user_ns['Out'] = self.output_hist
407 411
408 412 # Object variable to store code object waiting execution. This is
409 413 # used mainly by the multithreaded shells, but it can come in handy in
410 414 # other situations. No need to use a Queue here, since it's a single
411 415 # item which gets cleared once run.
412 416 self.code_to_run = None
413 417
414 418 # Job manager (for jobs run as background threads)
415 419 self.jobs = BackgroundJobManager()
416 420 # Put the job manager into builtins so it's always there.
417 421 __builtin__.jobs = self.jobs
418 422
419 423 # escapes for automatic behavior on the command line
420 424 self.ESC_SHELL = '!'
421 425 self.ESC_HELP = '?'
422 426 self.ESC_MAGIC = '%'
423 427 self.ESC_QUOTE = ','
424 428 self.ESC_QUOTE2 = ';'
425 429 self.ESC_PAREN = '/'
426 430
427 431 # And their associated handlers
428 432 self.esc_handlers = {self.ESC_PAREN : self.handle_auto,
429 433 self.ESC_QUOTE : self.handle_auto,
430 434 self.ESC_QUOTE2 : self.handle_auto,
431 435 self.ESC_MAGIC : self.handle_magic,
432 436 self.ESC_HELP : self.handle_help,
433 437 self.ESC_SHELL : self.handle_shell_escape,
434 438 }
435 439
436 440 # class initializations
437 441 Magic.__init__(self,self)
438 442
439 443 # Python source parser/formatter for syntax highlighting
440 444 pyformat = PyColorize.Parser().format
441 445 self.pycolorize = lambda src: pyformat(src,'str',self.rc['colors'])
442 446
443 447 # hooks holds pointers used for user-side customizations
444 448 self.hooks = Struct()
445 449
446 450 # Set all default hooks, defined in the IPython.hooks module.
447 451 hooks = IPython.hooks
448 452 for hook_name in hooks.__all__:
449 453 self.set_hook(hook_name,getattr(hooks,hook_name))
450 454
451 455 # Flag to mark unconditional exit
452 456 self.exit_now = False
453 457
454 458 self.usage_min = """\
455 459 An enhanced console for Python.
456 460 Some of its features are:
457 461 - Readline support if the readline library is present.
458 462 - Tab completion in the local namespace.
459 463 - Logging of input, see command-line options.
460 464 - System shell escape via ! , eg !ls.
461 465 - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.)
462 466 - Keeps track of locally defined variables via %who, %whos.
463 467 - Show object information with a ? eg ?x or x? (use ?? for more info).
464 468 """
465 469 if usage: self.usage = usage
466 470 else: self.usage = self.usage_min
467 471
468 472 # Storage
469 473 self.rc = rc # This will hold all configuration information
470 474 self.inputcache = []
471 475 self._boundcache = []
472 476 self.pager = 'less'
473 477 # temporary files used for various purposes. Deleted at exit.
474 478 self.tempfiles = []
475 479
476 480 # Keep track of readline usage (later set by init_readline)
477 481 self.has_readline = False
478 482
479 483 # template for logfile headers. It gets resolved at runtime by the
480 484 # logstart method.
481 485 self.loghead_tpl = \
482 486 """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE ***
483 487 #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW
484 488 #log# opts = %s
485 489 #log# args = %s
486 490 #log# It is safe to make manual edits below here.
487 491 #log#-----------------------------------------------------------------------
488 492 """
489 493 # for pushd/popd management
490 494 try:
491 495 self.home_dir = get_home_dir()
492 496 except HomeDirError,msg:
493 497 fatal(msg)
494 498
495 499 self.dir_stack = [os.getcwd().replace(self.home_dir,'~')]
496 500
497 501 # Functions to call the underlying shell.
498 502
499 503 # utility to expand user variables via Itpl
500 504 self.var_expand = lambda cmd: str(ItplNS(cmd.replace('#','\#'),
501 505 self.user_ns))
502 506 # The first is similar to os.system, but it doesn't return a value,
503 507 # and it allows interpolation of variables in the user's namespace.
504 508 self.system = lambda cmd: shell(self.var_expand(cmd),
505 509 header='IPython system call: ',
506 510 verbose=self.rc.system_verbose)
507 511 # These are for getoutput and getoutputerror:
508 512 self.getoutput = lambda cmd: \
509 513 getoutput(self.var_expand(cmd),
510 514 header='IPython system call: ',
511 515 verbose=self.rc.system_verbose)
512 516 self.getoutputerror = lambda cmd: \
513 517 getoutputerror(str(ItplNS(cmd.replace('#','\#'),
514 518 self.user_ns)),
515 519 header='IPython system call: ',
516 520 verbose=self.rc.system_verbose)
517 521
518 522 # RegExp for splitting line contents into pre-char//first
519 523 # word-method//rest. For clarity, each group in on one line.
520 524
521 525 # WARNING: update the regexp if the above escapes are changed, as they
522 526 # are hardwired in.
523 527
524 528 # Don't get carried away with trying to make the autocalling catch too
525 529 # much: it's better to be conservative rather than to trigger hidden
526 530 # evals() somewhere and end up causing side effects.
527 531
528 532 self.line_split = re.compile(r'^([\s*,;/])'
529 533 r'([\?\w\.]+\w*\s*)'
530 534 r'(\(?.*$)')
531 535
532 536 # Original re, keep around for a while in case changes break something
533 537 #self.line_split = re.compile(r'(^[\s*!\?%,/]?)'
534 538 # r'(\s*[\?\w\.]+\w*\s*)'
535 539 # r'(\(?.*$)')
536 540
537 541 # RegExp to identify potential function names
538 542 self.re_fun_name = re.compile(r'[a-zA-Z_]([a-zA-Z0-9_.]*) *$')
539 543 # RegExp to exclude strings with this start from autocalling
540 544 self.re_exclude_auto = re.compile('^[!=()<>,\*/\+-]|^is ')
541 545
542 546 # try to catch also methods for stuff in lists/tuples/dicts: off
543 547 # (experimental). For this to work, the line_split regexp would need
544 548 # to be modified so it wouldn't break things at '['. That line is
545 549 # nasty enough that I shouldn't change it until I can test it _well_.
546 550 #self.re_fun_name = re.compile (r'[a-zA-Z_]([a-zA-Z0-9_.\[\]]*) ?$')
547 551
548 552 # keep track of where we started running (mainly for crash post-mortem)
549 553 self.starting_dir = os.getcwd()
550 554
551 555 # Various switches which can be set
552 556 self.CACHELENGTH = 5000 # this is cheap, it's just text
553 557 self.BANNER = "Python %(version)s on %(platform)s\n" % sys.__dict__
554 558 self.banner2 = banner2
555 559
556 560 # TraceBack handlers:
557 561
558 562 # Syntax error handler.
559 563 self.SyntaxTB = SyntaxTB(color_scheme='NoColor')
560 564
561 565 # The interactive one is initialized with an offset, meaning we always
562 566 # want to remove the topmost item in the traceback, which is our own
563 567 # internal code. Valid modes: ['Plain','Context','Verbose']
564 568 self.InteractiveTB = ultraTB.AutoFormattedTB(mode = 'Plain',
565 569 color_scheme='NoColor',
566 570 tb_offset = 1)
567 571
568 572 # IPython itself shouldn't crash. This will produce a detailed
569 573 # post-mortem if it does. But we only install the crash handler for
570 574 # non-threaded shells, the threaded ones use a normal verbose reporter
571 575 # and lose the crash handler. This is because exceptions in the main
572 576 # thread (such as in GUI code) propagate directly to sys.excepthook,
573 577 # and there's no point in printing crash dumps for every user exception.
574 578 if self.isthreaded:
575 579 sys.excepthook = ultraTB.FormattedTB()
576 580 else:
577 581 from IPython import CrashHandler
578 582 sys.excepthook = CrashHandler.CrashHandler(self)
579 583
580 584 # The instance will store a pointer to this, so that runtime code
581 585 # (such as magics) can access it. This is because during the
582 586 # read-eval loop, it gets temporarily overwritten (to deal with GUI
583 587 # frameworks).
584 588 self.sys_excepthook = sys.excepthook
585 589
586 590 # and add any custom exception handlers the user may have specified
587 591 self.set_custom_exc(*custom_exceptions)
588 592
589 593 # Object inspector
590 594 self.inspector = OInspect.Inspector(OInspect.InspectColors,
591 595 PyColorize.ANSICodeColors,
592 596 'NoColor')
593 597 # indentation management
594 598 self.autoindent = False
595 599 self.indent_current_nsp = 0
596 600 self.indent_current = '' # actual indent string
597 601
598 602 # Make some aliases automatically
599 603 # Prepare list of shell aliases to auto-define
600 604 if os.name == 'posix':
601 605 auto_alias = ('mkdir mkdir', 'rmdir rmdir',
602 606 'mv mv -i','rm rm -i','cp cp -i',
603 607 'cat cat','less less','clear clear',
604 608 # a better ls
605 609 'ls ls -F',
606 610 # long ls
607 611 'll ls -lF',
608 612 # color ls
609 613 'lc ls -F -o --color',
610 614 # ls normal files only
611 615 'lf ls -F -o --color %l | grep ^-',
612 616 # ls symbolic links
613 617 'lk ls -F -o --color %l | grep ^l',
614 618 # directories or links to directories,
615 619 'ldir ls -F -o --color %l | grep /$',
616 620 # things which are executable
617 621 'lx ls -F -o --color %l | grep ^-..x',
618 622 )
619 623 elif os.name in ['nt','dos']:
620 624 auto_alias = ('dir dir /on', 'ls dir /on',
621 625 'ddir dir /ad /on', 'ldir dir /ad /on',
622 626 'mkdir mkdir','rmdir rmdir','echo echo',
623 627 'ren ren','cls cls','copy copy')
624 628 else:
625 629 auto_alias = ()
626 630 self.auto_alias = map(lambda s:s.split(None,1),auto_alias)
627 631 # Call the actual (public) initializer
628 632 self.init_auto_alias()
629 633 # end __init__
630 634
631 635 def post_config_initialization(self):
632 636 """Post configuration init method
633 637
634 638 This is called after the configuration files have been processed to
635 639 'finalize' the initialization."""
636 640
637 641 rc = self.rc
638 642
639 643 # Load readline proper
640 644 if rc.readline:
641 645 self.init_readline()
642 646
643 647 # log system
644 648 self.logger = Logger(self,logfname='ipython_log.py',logmode='rotate')
645 649 # local shortcut, this is used a LOT
646 650 self.log = self.logger.log
647 651
648 652 # Initialize cache, set in/out prompts and printing system
649 653 self.outputcache = CachedOutput(self,
650 654 rc.cache_size,
651 655 rc.pprint,
652 656 input_sep = rc.separate_in,
653 657 output_sep = rc.separate_out,
654 658 output_sep2 = rc.separate_out2,
655 659 ps1 = rc.prompt_in1,
656 660 ps2 = rc.prompt_in2,
657 661 ps_out = rc.prompt_out,
658 662 pad_left = rc.prompts_pad_left)
659 663
660 664 # user may have over-ridden the default print hook:
661 665 try:
662 666 self.outputcache.__class__.display = self.hooks.display
663 667 except AttributeError:
664 668 pass
665 669
666 670 # I don't like assigning globally to sys, because it means when embedding
667 671 # instances, each embedded instance overrides the previous choice. But
668 672 # sys.displayhook seems to be called internally by exec, so I don't see a
669 673 # way around it.
670 674 sys.displayhook = self.outputcache
671 675
672 676 # Set user colors (don't do it in the constructor above so that it
673 677 # doesn't crash if colors option is invalid)
674 678 self.magic_colors(rc.colors)
675 679
676 680 # Set calling of pdb on exceptions
677 681 self.call_pdb = rc.pdb
678 682
679 683 # Load user aliases
680 684 for alias in rc.alias:
681 685 self.magic_alias(alias)
682 686
683 687 # dynamic data that survives through sessions
684 688 # XXX make the filename a config option?
685 689 persist_base = 'persist'
686 690 if rc.profile:
687 691 persist_base += '_%s' % rc.profile
688 692 self.persist_fname = os.path.join(rc.ipythondir,persist_base)
689 693
690 694 try:
691 695 self.persist = pickle.load(file(self.persist_fname))
692 696 except:
693 697 self.persist = {}
694 698
695 699
696 700 for (key, value) in [(k[2:],v) for (k,v) in self.persist.items() if k.startswith('S:')]:
697 701 try:
698 702 obj = pickle.loads(value)
699 703 except:
700 704
701 705 print "Unable to restore variable '%s', ignoring (use %%store -d to forget!)" % key
702 706 print "The error was:",sys.exc_info()[0]
703 707 continue
704 708
705 709
706 710 self.user_ns[key] = obj
707 711
708 712
709 713
710 714
711 715 def set_hook(self,name,hook):
712 716 """set_hook(name,hook) -> sets an internal IPython hook.
713 717
714 718 IPython exposes some of its internal API as user-modifiable hooks. By
715 719 resetting one of these hooks, you can modify IPython's behavior to
716 720 call at runtime your own routines."""
717 721
718 722 # At some point in the future, this should validate the hook before it
719 723 # accepts it. Probably at least check that the hook takes the number
720 724 # of args it's supposed to.
721 725 setattr(self.hooks,name,new.instancemethod(hook,self,self.__class__))
722 726
723 727 def set_custom_exc(self,exc_tuple,handler):
724 728 """set_custom_exc(exc_tuple,handler)
725 729
726 730 Set a custom exception handler, which will be called if any of the
727 731 exceptions in exc_tuple occur in the mainloop (specifically, in the
728 732 runcode() method.
729 733
730 734 Inputs:
731 735
732 736 - exc_tuple: a *tuple* of valid exceptions to call the defined
733 737 handler for. It is very important that you use a tuple, and NOT A
734 738 LIST here, because of the way Python's except statement works. If
735 739 you only want to trap a single exception, use a singleton tuple:
736 740
737 741 exc_tuple == (MyCustomException,)
738 742
739 743 - handler: this must be defined as a function with the following
740 744 basic interface: def my_handler(self,etype,value,tb).
741 745
742 746 This will be made into an instance method (via new.instancemethod)
743 747 of IPython itself, and it will be called if any of the exceptions
744 748 listed in the exc_tuple are caught. If the handler is None, an
745 749 internal basic one is used, which just prints basic info.
746 750
747 751 WARNING: by putting in your own exception handler into IPython's main
748 752 execution loop, you run a very good chance of nasty crashes. This
749 753 facility should only be used if you really know what you are doing."""
750 754
751 755 assert type(exc_tuple)==type(()) , \
752 756 "The custom exceptions must be given AS A TUPLE."
753 757
754 758 def dummy_handler(self,etype,value,tb):
755 759 print '*** Simple custom exception handler ***'
756 760 print 'Exception type :',etype
757 761 print 'Exception value:',value
758 762 print 'Traceback :',tb
759 763 print 'Source code :','\n'.join(self.buffer)
760 764
761 765 if handler is None: handler = dummy_handler
762 766
763 767 self.CustomTB = new.instancemethod(handler,self,self.__class__)
764 768 self.custom_exceptions = exc_tuple
765 769
766 770 def set_custom_completer(self,completer,pos=0):
767 771 """set_custom_completer(completer,pos=0)
768 772
769 773 Adds a new custom completer function.
770 774
771 775 The position argument (defaults to 0) is the index in the completers
772 776 list where you want the completer to be inserted."""
773 777
774 778 newcomp = new.instancemethod(completer,self.Completer,
775 779 self.Completer.__class__)
776 780 self.Completer.matchers.insert(pos,newcomp)
777 781
778 782 def _get_call_pdb(self):
779 783 return self._call_pdb
780 784
781 785 def _set_call_pdb(self,val):
782 786
783 787 if val not in (0,1,False,True):
784 788 raise ValueError,'new call_pdb value must be boolean'
785 789
786 790 # store value in instance
787 791 self._call_pdb = val
788 792
789 793 # notify the actual exception handlers
790 794 self.InteractiveTB.call_pdb = val
791 795 if self.isthreaded:
792 796 try:
793 797 self.sys_excepthook.call_pdb = val
794 798 except:
795 799 warn('Failed to activate pdb for threaded exception handler')
796 800
797 801 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
798 802 'Control auto-activation of pdb at exceptions')
799 803
800 804 def complete(self,text):
801 805 """Return a sorted list of all possible completions on text.
802 806
803 807 Inputs:
804 808
805 809 - text: a string of text to be completed on.
806 810
807 811 This is a wrapper around the completion mechanism, similar to what
808 812 readline does at the command line when the TAB key is hit. By
809 813 exposing it as a method, it can be used by other non-readline
810 814 environments (such as GUIs) for text completion.
811 815
812 816 Simple usage example:
813 817
814 818 In [1]: x = 'hello'
815 819
816 820 In [2]: __IP.complete('x.l')
817 821 Out[2]: ['x.ljust', 'x.lower', 'x.lstrip']"""
818 822
819 823 complete = self.Completer.complete
820 824 state = 0
821 825 # use a dict so we get unique keys, since ipyhton's multiple
822 826 # completers can return duplicates.
823 827 comps = {}
824 828 while True:
825 829 newcomp = complete(text,state)
826 830 if newcomp is None:
827 831 break
828 832 comps[newcomp] = 1
829 833 state += 1
830 834 outcomps = comps.keys()
831 835 outcomps.sort()
832 836 return outcomps
833 837
834 838 def set_completer_frame(self, frame):
835 839 if frame:
836 840 self.Completer.namespace = frame.f_locals
837 841 self.Completer.global_namespace = frame.f_globals
838 842 else:
839 843 self.Completer.namespace = self.user_ns
840 844 self.Completer.global_namespace = self.user_global_ns
841 845
842 846 def init_auto_alias(self):
843 847 """Define some aliases automatically.
844 848
845 849 These are ALL parameter-less aliases"""
846 850 for alias,cmd in self.auto_alias:
847 851 self.alias_table[alias] = (0,cmd)
848 852
849 853 def alias_table_validate(self,verbose=0):
850 854 """Update information about the alias table.
851 855
852 856 In particular, make sure no Python keywords/builtins are in it."""
853 857
854 858 no_alias = self.no_alias
855 859 for k in self.alias_table.keys():
856 860 if k in no_alias:
857 861 del self.alias_table[k]
858 862 if verbose:
859 863 print ("Deleting alias <%s>, it's a Python "
860 864 "keyword or builtin." % k)
861 865
862 866 def set_autoindent(self,value=None):
863 867 """Set the autoindent flag, checking for readline support.
864 868
865 869 If called with no arguments, it acts as a toggle."""
866 870
867 871 if not self.has_readline:
868 872 if os.name == 'posix':
869 873 warn("The auto-indent feature requires the readline library")
870 874 self.autoindent = 0
871 875 return
872 876 if value is None:
873 877 self.autoindent = not self.autoindent
874 878 else:
875 879 self.autoindent = value
876 880
877 881 def rc_set_toggle(self,rc_field,value=None):
878 882 """Set or toggle a field in IPython's rc config. structure.
879 883
880 884 If called with no arguments, it acts as a toggle.
881 885
882 886 If called with a non-existent field, the resulting AttributeError
883 887 exception will propagate out."""
884 888
885 889 rc_val = getattr(self.rc,rc_field)
886 890 if value is None:
887 891 value = not rc_val
888 892 setattr(self.rc,rc_field,value)
889 893
890 894 def user_setup(self,ipythondir,rc_suffix,mode='install'):
891 895 """Install the user configuration directory.
892 896
893 897 Can be called when running for the first time or to upgrade the user's
894 898 .ipython/ directory with the mode parameter. Valid modes are 'install'
895 899 and 'upgrade'."""
896 900
897 901 def wait():
898 902 try:
899 903 raw_input("Please press <RETURN> to start IPython.")
900 904 except EOFError:
901 905 print >> Term.cout
902 906 print '*'*70
903 907
904 908 cwd = os.getcwd() # remember where we started
905 909 glb = glob.glob
906 910 print '*'*70
907 911 if mode == 'install':
908 912 print \
909 913 """Welcome to IPython. I will try to create a personal configuration directory
910 914 where you can customize many aspects of IPython's functionality in:\n"""
911 915 else:
912 916 print 'I am going to upgrade your configuration in:'
913 917
914 918 print ipythondir
915 919
916 920 rcdirend = os.path.join('IPython','UserConfig')
917 921 cfg = lambda d: os.path.join(d,rcdirend)
918 922 try:
919 923 rcdir = filter(os.path.isdir,map(cfg,sys.path))[0]
920 924 except IOError:
921 925 warning = """
922 926 Installation error. IPython's directory was not found.
923 927
924 928 Check the following:
925 929
926 930 The ipython/IPython directory should be in a directory belonging to your
927 931 PYTHONPATH environment variable (that is, it should be in a directory
928 932 belonging to sys.path). You can copy it explicitly there or just link to it.
929 933
930 934 IPython will proceed with builtin defaults.
931 935 """
932 936 warn(warning)
933 937 wait()
934 938 return
935 939
936 940 if mode == 'install':
937 941 try:
938 942 shutil.copytree(rcdir,ipythondir)
939 943 os.chdir(ipythondir)
940 944 rc_files = glb("ipythonrc*")
941 945 for rc_file in rc_files:
942 946 os.rename(rc_file,rc_file+rc_suffix)
943 947 except:
944 948 warning = """
945 949
946 950 There was a problem with the installation:
947 951 %s
948 952 Try to correct it or contact the developers if you think it's a bug.
949 953 IPython will proceed with builtin defaults.""" % sys.exc_info()[1]
950 954 warn(warning)
951 955 wait()
952 956 return
953 957
954 958 elif mode == 'upgrade':
955 959 try:
956 960 os.chdir(ipythondir)
957 961 except:
958 962 print """
959 963 Can not upgrade: changing to directory %s failed. Details:
960 964 %s
961 965 """ % (ipythondir,sys.exc_info()[1])
962 966 wait()
963 967 return
964 968 else:
965 969 sources = glb(os.path.join(rcdir,'[A-Za-z]*'))
966 970 for new_full_path in sources:
967 971 new_filename = os.path.basename(new_full_path)
968 972 if new_filename.startswith('ipythonrc'):
969 973 new_filename = new_filename + rc_suffix
970 974 # The config directory should only contain files, skip any
971 975 # directories which may be there (like CVS)
972 976 if os.path.isdir(new_full_path):
973 977 continue
974 978 if os.path.exists(new_filename):
975 979 old_file = new_filename+'.old'
976 980 if os.path.exists(old_file):
977 981 os.remove(old_file)
978 982 os.rename(new_filename,old_file)
979 983 shutil.copy(new_full_path,new_filename)
980 984 else:
981 985 raise ValueError,'unrecognized mode for install:',`mode`
982 986
983 987 # Fix line-endings to those native to each platform in the config
984 988 # directory.
985 989 try:
986 990 os.chdir(ipythondir)
987 991 except:
988 992 print """
989 993 Problem: changing to directory %s failed.
990 994 Details:
991 995 %s
992 996
993 997 Some configuration files may have incorrect line endings. This should not
994 998 cause any problems during execution. """ % (ipythondir,sys.exc_info()[1])
995 999 wait()
996 1000 else:
997 1001 for fname in glb('ipythonrc*'):
998 1002 try:
999 1003 native_line_ends(fname,backup=0)
1000 1004 except IOError:
1001 1005 pass
1002 1006
1003 1007 if mode == 'install':
1004 1008 print """
1005 1009 Successful installation!
1006 1010
1007 1011 Please read the sections 'Initial Configuration' and 'Quick Tips' in the
1008 1012 IPython manual (there are both HTML and PDF versions supplied with the
1009 1013 distribution) to make sure that your system environment is properly configured
1010 1014 to take advantage of IPython's features."""
1011 1015 else:
1012 1016 print """
1013 1017 Successful upgrade!
1014 1018
1015 1019 All files in your directory:
1016 1020 %(ipythondir)s
1017 1021 which would have been overwritten by the upgrade were backed up with a .old
1018 1022 extension. If you had made particular customizations in those files you may
1019 1023 want to merge them back into the new files.""" % locals()
1020 1024 wait()
1021 1025 os.chdir(cwd)
1022 1026 # end user_setup()
1023 1027
1024 1028 def atexit_operations(self):
1025 1029 """This will be executed at the time of exit.
1026 1030
1027 1031 Saving of persistent data should be performed here. """
1028 1032
1029 1033 # input history
1030 1034 self.savehist()
1031 1035
1032 1036 # Cleanup all tempfiles left around
1033 1037 for tfile in self.tempfiles:
1034 1038 try:
1035 1039 os.unlink(tfile)
1036 1040 except OSError:
1037 1041 pass
1038 1042
1039 1043 # save the "persistent data" catch-all dictionary
1040 1044 try:
1041 1045 pickle.dump(self.persist, open(self.persist_fname,"w"))
1042 1046 except:
1043 1047 print "*** ERROR *** persistent data saving failed."
1044 1048
1045 1049 def savehist(self):
1046 1050 """Save input history to a file (via readline library)."""
1047 1051 try:
1048 1052 self.readline.write_history_file(self.histfile)
1049 1053 except:
1050 1054 print 'Unable to save IPython command history to file: ' + \
1051 1055 `self.histfile`
1052 1056
1053 1057 def pre_readline(self):
1054 1058 """readline hook to be used at the start of each line.
1055 1059
1056 1060 Currently it handles auto-indent only."""
1057 1061
1058 1062 self.readline.insert_text(self.indent_current)
1059 1063
1060 1064 def init_readline(self):
1061 1065 """Command history completion/saving/reloading."""
1062 1066 try:
1063 1067 import readline
1064 1068 except ImportError:
1065 1069 self.has_readline = 0
1066 1070 self.readline = None
1067 1071 # no point in bugging windows users with this every time:
1068 1072 if os.name == 'posix':
1069 1073 warn('Readline services not available on this platform.')
1070 1074 else:
1071 1075 import atexit
1072 1076 from IPython.completer import IPCompleter
1073 1077 self.Completer = IPCompleter(self,
1074 1078 self.user_ns,
1075 1079 self.user_global_ns,
1076 1080 self.rc.readline_omit__names,
1077 1081 self.alias_table)
1078 1082
1079 1083 # Platform-specific configuration
1080 1084 if os.name == 'nt':
1081 1085 self.readline_startup_hook = readline.set_pre_input_hook
1082 1086 else:
1083 1087 self.readline_startup_hook = readline.set_startup_hook
1084 1088
1085 1089 # Load user's initrc file (readline config)
1086 1090 inputrc_name = os.environ.get('INPUTRC')
1087 1091 if inputrc_name is None:
1088 1092 home_dir = get_home_dir()
1089 1093 if home_dir is not None:
1090 1094 inputrc_name = os.path.join(home_dir,'.inputrc')
1091 1095 if os.path.isfile(inputrc_name):
1092 1096 try:
1093 1097 readline.read_init_file(inputrc_name)
1094 1098 except:
1095 1099 warn('Problems reading readline initialization file <%s>'
1096 1100 % inputrc_name)
1097 1101
1098 1102 self.has_readline = 1
1099 1103 self.readline = readline
1100 1104 # save this in sys so embedded copies can restore it properly
1101 1105 sys.ipcompleter = self.Completer.complete
1102 1106 readline.set_completer(self.Completer.complete)
1103 1107
1104 1108 # Configure readline according to user's prefs
1105 1109 for rlcommand in self.rc.readline_parse_and_bind:
1106 1110 readline.parse_and_bind(rlcommand)
1107 1111
1108 1112 # remove some chars from the delimiters list
1109 1113 delims = readline.get_completer_delims()
1110 1114 delims = delims.translate(string._idmap,
1111 1115 self.rc.readline_remove_delims)
1112 1116 readline.set_completer_delims(delims)
1113 1117 # otherwise we end up with a monster history after a while:
1114 1118 readline.set_history_length(1000)
1115 1119 try:
1116 1120 #print '*** Reading readline history' # dbg
1117 1121 readline.read_history_file(self.histfile)
1118 1122 except IOError:
1119 1123 pass # It doesn't exist yet.
1120 1124
1121 1125 atexit.register(self.atexit_operations)
1122 1126 del atexit
1123 1127
1124 1128 # Configure auto-indent for all platforms
1125 1129 self.set_autoindent(self.rc.autoindent)
1126 1130
1127 1131 def _should_recompile(self,e):
1128 1132 """Utility routine for edit_syntax_error"""
1129 1133
1130 1134 if e.filename in ('<ipython console>','<input>','<string>',
1131 1135 '<console>'):
1132 1136 return False
1133 1137 try:
1134 1138 if not ask_yes_no('Return to editor to correct syntax error? '
1135 1139 '[Y/n] ','y'):
1136 1140 return False
1137 1141 except EOFError:
1138 1142 return False
1139 1143 self.hooks.fix_error_editor(e.filename,e.lineno,e.offset,e.msg)
1140 1144 return True
1141 1145
1142 1146 def edit_syntax_error(self):
1143 1147 """The bottom half of the syntax error handler called in the main loop.
1144 1148
1145 1149 Loop until syntax error is fixed or user cancels.
1146 1150 """
1147 1151
1148 1152 while self.SyntaxTB.last_syntax_error:
1149 1153 # copy and clear last_syntax_error
1150 1154 err = self.SyntaxTB.clear_err_state()
1151 1155 if not self._should_recompile(err):
1152 1156 return
1153 1157 try:
1154 1158 # may set last_syntax_error again if a SyntaxError is raised
1155 1159 self.safe_execfile(err.filename,self.shell.user_ns)
1156 1160 except:
1157 1161 self.showtraceback()
1158 1162 else:
1159 1163 f = file(err.filename)
1160 1164 try:
1161 1165 sys.displayhook(f.read())
1162 1166 finally:
1163 1167 f.close()
1164 1168
1165 1169 def showsyntaxerror(self, filename=None):
1166 1170 """Display the syntax error that just occurred.
1167 1171
1168 1172 This doesn't display a stack trace because there isn't one.
1169 1173
1170 1174 If a filename is given, it is stuffed in the exception instead
1171 1175 of what was there before (because Python's parser always uses
1172 1176 "<string>" when reading from a string).
1173 1177 """
1174 type, value, sys.last_traceback = sys.exc_info()
1175 sys.last_type = type
1176 sys.last_value = value
1177 if filename and type is SyntaxError:
1178 etype, value, last_traceback = sys.exc_info()
1179 if filename and etype is SyntaxError:
1178 1180 # Work hard to stuff the correct filename in the exception
1179 1181 try:
1180 1182 msg, (dummy_filename, lineno, offset, line) = value
1181 1183 except:
1182 1184 # Not the format we expect; leave it alone
1183 1185 pass
1184 1186 else:
1185 1187 # Stuff in the right filename
1186 1188 try:
1187 1189 # Assume SyntaxError is a class exception
1188 1190 value = SyntaxError(msg, (filename, lineno, offset, line))
1189 1191 except:
1190 1192 # If that failed, assume SyntaxError is a string
1191 1193 value = msg, (filename, lineno, offset, line)
1192 self.SyntaxTB(type,value,[])
1194 self.SyntaxTB(etype,value,[])
1193 1195
1194 1196 def debugger(self):
1195 1197 """Call the pdb debugger."""
1196 1198
1197 1199 if not self.rc.pdb:
1198 1200 return
1199 1201 pdb.pm()
1200 1202
1201 1203 def showtraceback(self,exc_tuple = None,filename=None):
1202 1204 """Display the exception that just occurred."""
1203 1205
1204 1206 # Though this won't be called by syntax errors in the input line,
1205 1207 # there may be SyntaxError cases whith imported code.
1206 1208 if exc_tuple is None:
1207 1209 type, value, tb = sys.exc_info()
1208 1210 else:
1209 1211 type, value, tb = exc_tuple
1210 1212 if type is SyntaxError:
1211 1213 self.showsyntaxerror(filename)
1212 1214 else:
1213 sys.last_type = type
1214 sys.last_value = value
1215 sys.last_traceback = tb
1216 1215 self.InteractiveTB()
1217 1216 if self.InteractiveTB.call_pdb and self.has_readline:
1218 1217 # pdb mucks up readline, fix it back
1219 1218 self.readline.set_completer(self.Completer.complete)
1220 1219
1221 1220 def update_cache(self, line):
1222 1221 """puts line into cache"""
1223 self.inputcache.insert(0, line) # This copies the cache every time ... :-(
1222 return # dbg
1223
1224 # This copies the cache every time ... :-(
1225 self.inputcache.insert(0, line)
1224 1226 if len(self.inputcache) >= self.CACHELENGTH:
1225 1227 self.inputcache.pop() # This doesn't :-)
1226 1228
1227 1229 def mainloop(self,banner=None):
1228 1230 """Creates the local namespace and starts the mainloop.
1229 1231
1230 1232 If an optional banner argument is given, it will override the
1231 1233 internally created default banner."""
1232 1234
1233 1235 if self.rc.c: # Emulate Python's -c option
1234 1236 self.exec_init_cmd()
1235 1237 if banner is None:
1236 1238 if self.rc.banner:
1237 1239 banner = self.BANNER+self.banner2
1238 1240 else:
1239 1241 banner = ''
1240 1242 self.interact(banner)
1241 1243
1242 1244 def exec_init_cmd(self):
1243 1245 """Execute a command given at the command line.
1244 1246
1245 1247 This emulates Python's -c option."""
1246 1248
1247 1249 sys.argv = ['-c']
1248 1250 self.push(self.rc.c)
1249 1251
1250 1252 def embed_mainloop(self,header='',local_ns=None,global_ns=None,stack_depth=0):
1251 1253 """Embeds IPython into a running python program.
1252 1254
1253 1255 Input:
1254 1256
1255 1257 - header: An optional header message can be specified.
1256 1258
1257 1259 - local_ns, global_ns: working namespaces. If given as None, the
1258 1260 IPython-initialized one is updated with __main__.__dict__, so that
1259 1261 program variables become visible but user-specific configuration
1260 1262 remains possible.
1261 1263
1262 1264 - stack_depth: specifies how many levels in the stack to go to
1263 1265 looking for namespaces (when local_ns and global_ns are None). This
1264 1266 allows an intermediate caller to make sure that this function gets
1265 1267 the namespace from the intended level in the stack. By default (0)
1266 1268 it will get its locals and globals from the immediate caller.
1267 1269
1268 1270 Warning: it's possible to use this in a program which is being run by
1269 1271 IPython itself (via %run), but some funny things will happen (a few
1270 1272 globals get overwritten). In the future this will be cleaned up, as
1271 1273 there is no fundamental reason why it can't work perfectly."""
1272 1274
1273 1275 # Get locals and globals from caller
1274 1276 if local_ns is None or global_ns is None:
1275 1277 call_frame = sys._getframe(stack_depth).f_back
1276 1278
1277 1279 if local_ns is None:
1278 1280 local_ns = call_frame.f_locals
1279 1281 if global_ns is None:
1280 1282 global_ns = call_frame.f_globals
1281 1283
1282 1284 # Update namespaces and fire up interpreter
1283 1285 self.user_ns = local_ns
1284 1286 self.user_global_ns = global_ns
1285 1287
1286 1288 # Patch for global embedding to make sure that things don't overwrite
1287 1289 # user globals accidentally. Thanks to Richard <rxe@renre-europe.com>
1288 1290 # FIXME. Test this a bit more carefully (the if.. is new)
1289 1291 if local_ns is None and global_ns is None:
1290 1292 self.user_global_ns.update(__main__.__dict__)
1291 1293
1292 1294 # make sure the tab-completer has the correct frame information, so it
1293 1295 # actually completes using the frame's locals/globals
1294 1296 self.set_completer_frame(call_frame)
1295 1297
1296 1298 self.interact(header)
1297 1299
1298 1300 def interact(self, banner=None):
1299 1301 """Closely emulate the interactive Python console.
1300 1302
1301 1303 The optional banner argument specify the banner to print
1302 1304 before the first interaction; by default it prints a banner
1303 1305 similar to the one printed by the real Python interpreter,
1304 1306 followed by the current class name in parentheses (so as not
1305 1307 to confuse this with the real interpreter -- since it's so
1306 1308 close!).
1307 1309
1308 1310 """
1309 1311 cprt = 'Type "copyright", "credits" or "license" for more information.'
1310 1312 if banner is None:
1311 1313 self.write("Python %s on %s\n%s\n(%s)\n" %
1312 1314 (sys.version, sys.platform, cprt,
1313 1315 self.__class__.__name__))
1314 1316 else:
1315 1317 self.write(banner)
1316 1318
1317 1319 more = 0
1318 1320
1319 1321 # Mark activity in the builtins
1320 1322 __builtin__.__dict__['__IPYTHON__active'] += 1
1321 1323
1322 # compiled regexps for autoindent management
1323 ini_spaces_re = re.compile(r'^(\s+)')
1324 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
1325
1326 1324 # exit_now is set by a call to %Exit or %Quit
1327 1325 while not self.exit_now:
1328 1326 try:
1329 1327 if more:
1330 1328 prompt = self.outputcache.prompt2
1331 1329 if self.autoindent:
1332 1330 self.readline_startup_hook(self.pre_readline)
1333 1331 else:
1334 1332 prompt = self.outputcache.prompt1
1335 1333 try:
1336 1334 line = self.raw_input(prompt,more)
1337 1335 if self.autoindent:
1338 1336 self.readline_startup_hook(None)
1339 1337 except EOFError:
1340 1338 if self.autoindent:
1341 1339 self.readline_startup_hook(None)
1342 1340 self.write("\n")
1343 1341 self.exit()
1344 1342 else:
1345 1343 more = self.push(line)
1346 # Auto-indent management
1347 if self.autoindent:
1348 if line:
1349 ini_spaces = ini_spaces_re.match(line)
1350 if ini_spaces:
1351 nspaces = ini_spaces.end()
1352 else:
1353 nspaces = 0
1354 self.indent_current_nsp = nspaces
1355
1356 if line[-1] == ':':
1357 self.indent_current_nsp += 4
1358 elif dedent_re.match(line):
1359 self.indent_current_nsp -= 4
1360 else:
1361 self.indent_current_nsp = 0
1362
1363 # indent_current is the actual string to be inserted
1364 # by the readline hooks for indentation
1365 self.indent_current = ' '* self.indent_current_nsp
1366 1344
1367 1345 if (self.SyntaxTB.last_syntax_error and
1368 1346 self.rc.autoedit_syntax):
1369 1347 self.edit_syntax_error()
1370 1348
1371 1349 except KeyboardInterrupt:
1372 1350 self.write("\nKeyboardInterrupt\n")
1373 1351 self.resetbuffer()
1374 1352 more = 0
1375 1353 # keep cache in sync with the prompt counter:
1376 1354 self.outputcache.prompt_count -= 1
1377 1355
1378 1356 if self.autoindent:
1379 1357 self.indent_current_nsp = 0
1380 1358 self.indent_current = ' '* self.indent_current_nsp
1381 1359
1382 1360 except bdb.BdbQuit:
1383 1361 warn("The Python debugger has exited with a BdbQuit exception.\n"
1384 1362 "Because of how pdb handles the stack, it is impossible\n"
1385 1363 "for IPython to properly format this particular exception.\n"
1386 1364 "IPython will resume normal operation.")
1387 1365
1388 1366 # We are off again...
1389 1367 __builtin__.__dict__['__IPYTHON__active'] -= 1
1390 1368
1391 1369 def excepthook(self, type, value, tb):
1392 1370 """One more defense for GUI apps that call sys.excepthook.
1393 1371
1394 1372 GUI frameworks like wxPython trap exceptions and call
1395 1373 sys.excepthook themselves. I guess this is a feature that
1396 1374 enables them to keep running after exceptions that would
1397 1375 otherwise kill their mainloop. This is a bother for IPython
1398 1376 which excepts to catch all of the program exceptions with a try:
1399 1377 except: statement.
1400 1378
1401 1379 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1402 1380 any app directly invokes sys.excepthook, it will look to the user like
1403 1381 IPython crashed. In order to work around this, we can disable the
1404 1382 CrashHandler and replace it with this excepthook instead, which prints a
1405 1383 regular traceback using our InteractiveTB. In this fashion, apps which
1406 1384 call sys.excepthook will generate a regular-looking exception from
1407 1385 IPython, and the CrashHandler will only be triggered by real IPython
1408 1386 crashes.
1409 1387
1410 1388 This hook should be used sparingly, only in places which are not likely
1411 1389 to be true IPython errors.
1412 1390 """
1413 1391
1414 1392 self.InteractiveTB(type, value, tb, tb_offset=0)
1415 1393 if self.InteractiveTB.call_pdb and self.has_readline:
1416 1394 self.readline.set_completer(self.Completer.complete)
1417 1395
1418 1396 def call_alias(self,alias,rest=''):
1419 1397 """Call an alias given its name and the rest of the line.
1420 1398
1421 1399 This function MUST be given a proper alias, because it doesn't make
1422 1400 any checks when looking up into the alias table. The caller is
1423 1401 responsible for invoking it only with a valid alias."""
1424 1402
1425 1403 #print 'ALIAS: <%s>+<%s>' % (alias,rest) # dbg
1426 1404 nargs,cmd = self.alias_table[alias]
1427 1405 # Expand the %l special to be the user's input line
1428 1406 if cmd.find('%l') >= 0:
1429 1407 cmd = cmd.replace('%l',rest)
1430 1408 rest = ''
1431 1409 if nargs==0:
1432 1410 # Simple, argument-less aliases
1433 1411 cmd = '%s %s' % (cmd,rest)
1434 1412 else:
1435 1413 # Handle aliases with positional arguments
1436 1414 args = rest.split(None,nargs)
1437 1415 if len(args)< nargs:
1438 1416 error('Alias <%s> requires %s arguments, %s given.' %
1439 1417 (alias,nargs,len(args)))
1440 1418 return
1441 1419 cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:]))
1442 1420 # Now call the macro, evaluating in the user's namespace
1443 1421 try:
1444 1422 self.system(cmd)
1445 1423 except:
1446 1424 self.showtraceback()
1447 1425
1426 def autoindent_update(self,line):
1427 """Keep track of the indent level."""
1428 if self.autoindent:
1429 if line:
1430 ini_spaces = ini_spaces_re.match(line)
1431 if ini_spaces:
1432 nspaces = ini_spaces.end()
1433 else:
1434 nspaces = 0
1435 self.indent_current_nsp = nspaces
1436
1437 if line[-1] == ':':
1438 self.indent_current_nsp += 4
1439 elif dedent_re.match(line):
1440 self.indent_current_nsp -= 4
1441 else:
1442 self.indent_current_nsp = 0
1443
1444 # indent_current is the actual string to be inserted
1445 # by the readline hooks for indentation
1446 self.indent_current = ' '* self.indent_current_nsp
1447
1448 1448 def runlines(self,lines):
1449 1449 """Run a string of one or more lines of source.
1450 1450
1451 1451 This method is capable of running a string containing multiple source
1452 1452 lines, as if they had been entered at the IPython prompt. Since it
1453 1453 exposes IPython's processing machinery, the given strings can contain
1454 1454 magic calls (%magic), special shell access (!cmd), etc."""
1455 1455
1456 1456 # We must start with a clean buffer, in case this is run from an
1457 1457 # interactive IPython session (via a magic, for example).
1458 1458 self.resetbuffer()
1459 1459 lines = lines.split('\n')
1460 1460 more = 0
1461 1461 for line in lines:
1462 1462 # skip blank lines so we don't mess up the prompt counter, but do
1463 1463 # NOT skip even a blank line if we are in a code block (more is
1464 1464 # true)
1465 #print 'rl line:<%s>' % line # dbg
1465 1466 if line or more:
1466 more = self.push((self.prefilter(line,more)))
1467 #print 'doit' # dbg
1468 newline = self.prefilter(line,more)
1469 more = self.push(newline)
1467 1470 # IPython's runsource returns None if there was an error
1468 1471 # compiling the code. This allows us to stop processing right
1469 1472 # away, so the user gets the error message at the right place.
1470 1473 if more is None:
1471 1474 break
1472 1475 # final newline in case the input didn't have it, so that the code
1473 1476 # actually does get executed
1474 1477 if more:
1475 1478 self.push('\n')
1476 1479
1477 1480 def runsource(self, source, filename='<input>', symbol='single'):
1478 1481 """Compile and run some source in the interpreter.
1479 1482
1480 1483 Arguments are as for compile_command().
1481 1484
1482 1485 One several things can happen:
1483 1486
1484 1487 1) The input is incorrect; compile_command() raised an
1485 1488 exception (SyntaxError or OverflowError). A syntax traceback
1486 1489 will be printed by calling the showsyntaxerror() method.
1487 1490
1488 1491 2) The input is incomplete, and more input is required;
1489 1492 compile_command() returned None. Nothing happens.
1490 1493
1491 1494 3) The input is complete; compile_command() returned a code
1492 1495 object. The code is executed by calling self.runcode() (which
1493 1496 also handles run-time exceptions, except for SystemExit).
1494 1497
1495 1498 The return value is:
1496 1499
1497 1500 - True in case 2
1498 1501
1499 1502 - False in the other cases, unless an exception is raised, where
1500 1503 None is returned instead. This can be used by external callers to
1501 1504 know whether to continue feeding input or not.
1502 1505
1503 1506 The return value can be used to decide whether to use sys.ps1 or
1504 1507 sys.ps2 to prompt the next line."""
1505 1508
1506 1509 try:
1507 1510 code = self.compile(source,filename,symbol)
1508 1511 except (OverflowError, SyntaxError, ValueError):
1509 1512 # Case 1
1510 1513 self.showsyntaxerror(filename)
1511 1514 return None
1512 1515
1513 1516 if code is None:
1514 1517 # Case 2
1515 1518 return True
1516 1519
1517 1520 # Case 3
1518 1521 # We store the code object so that threaded shells and
1519 1522 # custom exception handlers can access all this info if needed.
1520 1523 # The source corresponding to this can be obtained from the
1521 1524 # buffer attribute as '\n'.join(self.buffer).
1522 1525 self.code_to_run = code
1523 1526 # now actually execute the code object
1524 1527 if self.runcode(code) == 0:
1525 1528 return False
1526 1529 else:
1527 1530 return None
1528 1531
1529 1532 def runcode(self,code_obj):
1530 1533 """Execute a code object.
1531 1534
1532 1535 When an exception occurs, self.showtraceback() is called to display a
1533 1536 traceback.
1534 1537
1535 1538 Return value: a flag indicating whether the code to be run completed
1536 1539 successfully:
1537 1540
1538 1541 - 0: successful execution.
1539 1542 - 1: an error occurred.
1540 1543 """
1541 1544
1542 1545 # Set our own excepthook in case the user code tries to call it
1543 1546 # directly, so that the IPython crash handler doesn't get triggered
1544 1547 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
1545 1548
1546 1549 # we save the original sys.excepthook in the instance, in case config
1547 1550 # code (such as magics) needs access to it.
1548 1551 self.sys_excepthook = old_excepthook
1549 1552 outflag = 1 # happens in more places, so it's easier as default
1550 1553 try:
1551 1554 try:
1552 1555 # Embedded instances require separate global/local namespaces
1553 1556 # so they can see both the surrounding (local) namespace and
1554 1557 # the module-level globals when called inside another function.
1555 1558 if self.embedded:
1556 1559 exec code_obj in self.user_global_ns, self.user_ns
1557 1560 # Normal (non-embedded) instances should only have a single
1558 1561 # namespace for user code execution, otherwise functions won't
1559 1562 # see interactive top-level globals.
1560 1563 else:
1561 1564 exec code_obj in self.user_ns
1562 1565 finally:
1563 1566 # Reset our crash handler in place
1564 1567 sys.excepthook = old_excepthook
1565 1568 except SystemExit:
1566 1569 self.resetbuffer()
1567 1570 self.showtraceback()
1568 1571 warn("Type exit or quit to exit IPython "
1569 1572 "(%Exit or %Quit do so unconditionally).",level=1)
1570 1573 except self.custom_exceptions:
1571 1574 etype,value,tb = sys.exc_info()
1572 1575 self.CustomTB(etype,value,tb)
1573 1576 except:
1574 1577 self.showtraceback()
1575 1578 else:
1576 1579 outflag = 0
1577 1580 if softspace(sys.stdout, 0):
1578 1581 print
1579 1582 # Flush out code object which has been run (and source)
1580 1583 self.code_to_run = None
1581 1584 return outflag
1582 1585
1583 1586 def push(self, line):
1584 1587 """Push a line to the interpreter.
1585 1588
1586 1589 The line should not have a trailing newline; it may have
1587 1590 internal newlines. The line is appended to a buffer and the
1588 1591 interpreter's runsource() method is called with the
1589 1592 concatenated contents of the buffer as source. If this
1590 1593 indicates that the command was executed or invalid, the buffer
1591 1594 is reset; otherwise, the command is incomplete, and the buffer
1592 1595 is left as it was after the line was appended. The return
1593 1596 value is 1 if more input is required, 0 if the line was dealt
1594 1597 with in some way (this is the same as runsource()).
1595 1598
1596 1599 """
1597 1600 self.buffer.append(line)
1598 1601 more = self.runsource('\n'.join(self.buffer), self.filename)
1599 1602 if not more:
1600 1603 self.resetbuffer()
1601 1604 return more
1602 1605
1603 1606 def resetbuffer(self):
1604 1607 """Reset the input buffer."""
1605 1608 self.buffer[:] = []
1606 1609
1607 1610 def raw_input(self,prompt='',continue_prompt=False):
1608 1611 """Write a prompt and read a line.
1609 1612
1610 1613 The returned line does not include the trailing newline.
1611 1614 When the user enters the EOF key sequence, EOFError is raised.
1612 1615
1613 1616 Optional inputs:
1614 1617
1615 1618 - prompt(''): a string to be printed to prompt the user.
1616 1619
1617 1620 - continue_prompt(False): whether this line is the first one or a
1618 1621 continuation in a sequence of inputs.
1619 1622 """
1620 1623
1621 1624 line = raw_input_original(prompt)
1622 1625 # Try to be reasonably smart about not re-indenting pasted input more
1623 1626 # than necessary. We do this by trimming out the auto-indent initial
1624 1627 # spaces, if the user's actual input started itself with whitespace.
1625 1628 if self.autoindent:
1626 1629 line2 = line[self.indent_current_nsp:]
1627 1630 if line2[0:1] in (' ','\t'):
1628 1631 line = line2
1629 1632 return self.prefilter(line,continue_prompt)
1630 1633
1631 1634 def split_user_input(self,line):
1632 1635 """Split user input into pre-char, function part and rest."""
1633 1636
1634 1637 lsplit = self.line_split.match(line)
1635 1638 if lsplit is None: # no regexp match returns None
1636 1639 try:
1637 1640 iFun,theRest = line.split(None,1)
1638 1641 except ValueError:
1639 1642 iFun,theRest = line,''
1640 1643 pre = re.match('^(\s*)(.*)',line).groups()[0]
1641 1644 else:
1642 1645 pre,iFun,theRest = lsplit.groups()
1643 1646
1644 1647 #print 'line:<%s>' % line # dbg
1645 1648 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun.strip(),theRest) # dbg
1646 1649 return pre,iFun.strip(),theRest
1647 1650
1648 1651 def _prefilter(self, line, continue_prompt):
1649 1652 """Calls different preprocessors, depending on the form of line."""
1650 1653
1651 1654 # All handlers *must* return a value, even if it's blank ('').
1652 1655
1653 1656 # Lines are NOT logged here. Handlers should process the line as
1654 1657 # needed, update the cache AND log it (so that the input cache array
1655 1658 # stays synced).
1656 1659
1657 1660 # This function is _very_ delicate, and since it's also the one which
1658 1661 # determines IPython's response to user input, it must be as efficient
1659 1662 # as possible. For this reason it has _many_ returns in it, trying
1660 1663 # always to exit as quickly as it can figure out what it needs to do.
1661 1664
1662 1665 # This function is the main responsible for maintaining IPython's
1663 1666 # behavior respectful of Python's semantics. So be _very_ careful if
1664 1667 # making changes to anything here.
1665 1668
1666 1669 #.....................................................................
1667 1670 # Code begins
1668 1671
1669 1672 #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg
1670 1673
1671 1674 # save the line away in case we crash, so the post-mortem handler can
1672 1675 # record it
1673 1676 self._last_input_line = line
1674 1677
1675 1678 #print '***line: <%s>' % line # dbg
1676 1679
1677 1680 # the input history needs to track even empty lines
1678 1681 if not line.strip():
1679 1682 if not continue_prompt:
1680 1683 self.outputcache.prompt_count -= 1
1681 1684 return self.handle_normal(line,continue_prompt)
1682 1685 #return self.handle_normal('',continue_prompt)
1683 1686
1684 1687 # print '***cont',continue_prompt # dbg
1685 1688 # special handlers are only allowed for single line statements
1686 1689 if continue_prompt and not self.rc.multi_line_specials:
1687 1690 return self.handle_normal(line,continue_prompt)
1688 1691
1689 1692 # For the rest, we need the structure of the input
1690 1693 pre,iFun,theRest = self.split_user_input(line)
1691 1694 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
1692 1695
1693 1696 # First check for explicit escapes in the last/first character
1694 1697 handler = None
1695 1698 if line[-1] == self.ESC_HELP:
1696 1699 handler = self.esc_handlers.get(line[-1]) # the ? can be at the end
1697 1700 if handler is None:
1698 1701 # look at the first character of iFun, NOT of line, so we skip
1699 1702 # leading whitespace in multiline input
1700 1703 handler = self.esc_handlers.get(iFun[0:1])
1701 1704 if handler is not None:
1702 1705 return handler(line,continue_prompt,pre,iFun,theRest)
1703 1706 # Emacs ipython-mode tags certain input lines
1704 1707 if line.endswith('# PYTHON-MODE'):
1705 1708 return self.handle_emacs(line,continue_prompt)
1706 1709
1707 1710 # Next, check if we can automatically execute this thing
1708 1711
1709 1712 # Allow ! in multi-line statements if multi_line_specials is on:
1710 1713 if continue_prompt and self.rc.multi_line_specials and \
1711 1714 iFun.startswith(self.ESC_SHELL):
1712 1715 return self.handle_shell_escape(line,continue_prompt,
1713 1716 pre=pre,iFun=iFun,
1714 1717 theRest=theRest)
1715 1718
1716 1719 # Let's try to find if the input line is a magic fn
1717 1720 oinfo = None
1718 1721 if hasattr(self,'magic_'+iFun):
1722 # WARNING: _ofind uses getattr(), so it can consume generators and
1723 # cause other side effects.
1719 1724 oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
1720 1725 if oinfo['ismagic']:
1721 1726 # Be careful not to call magics when a variable assignment is
1722 1727 # being made (ls='hi', for example)
1723 1728 if self.rc.automagic and \
1724 1729 (len(theRest)==0 or theRest[0] not in '!=()<>,') and \
1725 1730 (self.rc.multi_line_specials or not continue_prompt):
1726 1731 return self.handle_magic(line,continue_prompt,
1727 1732 pre,iFun,theRest)
1728 1733 else:
1729 1734 return self.handle_normal(line,continue_prompt)
1730 1735
1731 1736 # If the rest of the line begins with an (in)equality, assginment or
1732 1737 # function call, we should not call _ofind but simply execute it.
1733 1738 # This avoids spurious geattr() accesses on objects upon assignment.
1734 1739 #
1735 1740 # It also allows users to assign to either alias or magic names true
1736 1741 # python variables (the magic/alias systems always take second seat to
1737 1742 # true python code).
1738 1743 if theRest and theRest[0] in '!=()':
1739 1744 return self.handle_normal(line,continue_prompt)
1740 1745
1741 1746 if oinfo is None:
1742 1747 oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
1743 1748
1744 1749 if not oinfo['found']:
1745 1750 return self.handle_normal(line,continue_prompt)
1746 1751 else:
1747 1752 #print 'iFun <%s> rest <%s>' % (iFun,theRest) # dbg
1748 1753 if oinfo['isalias']:
1749 1754 return self.handle_alias(line,continue_prompt,
1750 1755 pre,iFun,theRest)
1751 1756
1752 1757 if self.rc.autocall and \
1753 1758 not self.re_exclude_auto.match(theRest) and \
1754 1759 self.re_fun_name.match(iFun) and \
1755 1760 callable(oinfo['obj']) :
1756 1761 #print 'going auto' # dbg
1757 1762 return self.handle_auto(line,continue_prompt,pre,iFun,theRest)
1758 1763 else:
1759 1764 #print 'was callable?', callable(oinfo['obj']) # dbg
1760 1765 return self.handle_normal(line,continue_prompt)
1761 1766
1762 1767 # If we get here, we have a normal Python line. Log and return.
1763 1768 return self.handle_normal(line,continue_prompt)
1764 1769
1765 1770 def _prefilter_dumb(self, line, continue_prompt):
1766 1771 """simple prefilter function, for debugging"""
1767 1772 return self.handle_normal(line,continue_prompt)
1768 1773
1769 1774 # Set the default prefilter() function (this can be user-overridden)
1770 1775 prefilter = _prefilter
1771 1776
1772 1777 def handle_normal(self,line,continue_prompt=None,
1773 1778 pre=None,iFun=None,theRest=None):
1774 1779 """Handle normal input lines. Use as a template for handlers."""
1775 1780
1776 1781 # With autoindent on, we need some way to exit the input loop, and I
1777 1782 # don't want to force the user to have to backspace all the way to
1778 1783 # clear the line. The rule will be in this case, that either two
1779 1784 # lines of pure whitespace in a row, or a line of pure whitespace but
1780 1785 # of a size different to the indent level, will exit the input loop.
1781 1786 if (continue_prompt and self.autoindent and isspace(line) and
1782 1787 (line != self.indent_current or isspace(self.buffer[-1]))):
1783 1788 line = ''
1784 1789
1785 1790 self.log(line,continue_prompt)
1786 1791 self.update_cache(line)
1787 1792 return line
1788 1793
1789 1794 def handle_alias(self,line,continue_prompt=None,
1790 1795 pre=None,iFun=None,theRest=None):
1791 1796 """Handle alias input lines. """
1792 1797
1793 1798 theRest = esc_quotes(theRest)
1794 1799 # log the ipalias form, which doesn't depend on the instance name
1795 1800 line_log = 'ipalias("%s %s")' % (iFun,theRest)
1796 1801 self.log(line_log,continue_prompt)
1797 1802 self.update_cache(line_log)
1798 1803 # this is what actually gets executed
1799 1804 return "%s%s.call_alias('%s','%s')" % (pre,self.name,iFun,theRest)
1800 1805
1801 1806 def handle_shell_escape(self, line, continue_prompt=None,
1802 1807 pre=None,iFun=None,theRest=None):
1803 1808 """Execute the line in a shell, empty return value"""
1804 1809
1805 1810 #print 'line in :', `line` # dbg
1806 1811 # Example of a special handler. Others follow a similar pattern.
1807 1812 if continue_prompt: # multi-line statements
1808 1813 if iFun.startswith('!!'):
1809 1814 print 'SyntaxError: !! is not allowed in multiline statements'
1810 1815 return pre
1811 1816 else:
1812 1817 cmd = ("%s %s" % (iFun[1:],theRest)) #.replace('"','\\"')
1813 1818 #line_out = '%s%s.system("%s")' % (pre,self.name,cmd)
1814 1819 line_out = '%s%s.system(r"""%s"""[:-1])' % (pre,self.name,cmd + "_")
1815 1820 #line_out = ('%s%s.system(' % (pre,self.name)) + repr(cmd) + ')'
1816 1821 else: # single-line input
1817 1822 if line.startswith('!!'):
1818 1823 # rewrite iFun/theRest to properly hold the call to %sx and
1819 1824 # the actual command to be executed, so handle_magic can work
1820 1825 # correctly
1821 1826 theRest = '%s %s' % (iFun[2:],theRest)
1822 1827 iFun = 'sx'
1823 1828 return self.handle_magic('%ssx %s' % (self.ESC_MAGIC,line[2:]),
1824 1829 continue_prompt,pre,iFun,theRest)
1825 1830 else:
1826 1831 #cmd = esc_quotes(line[1:])
1827 1832 cmd=line[1:]
1828 1833 #line_out = '%s.system("%s")' % (self.name,cmd)
1829 1834 line_out = '%s.system(r"""%s"""[:-1])' % (self.name,cmd +"_")
1830 1835 #line_out = ('%s.system(' % self.name) + repr(cmd)+ ')'
1831 1836 # update cache/log and return
1832 1837 self.log(line_out,continue_prompt)
1833 1838 self.update_cache(line_out) # readline cache gets normal line
1834 1839 #print 'line out r:', `line_out` # dbg
1835 1840 #print 'line out s:', line_out # dbg
1836 1841 return line_out
1837 1842
1838 1843 def handle_magic(self, line, continue_prompt=None,
1839 1844 pre=None,iFun=None,theRest=None):
1840 1845 """Execute magic functions.
1841 1846
1842 1847 Also log them with a prepended # so the log is clean Python."""
1843 1848
1844 1849 cmd = '%sipmagic("%s")' % (pre,esc_quotes('%s %s' % (iFun,theRest)))
1845 1850 self.log(cmd,continue_prompt)
1846 1851 self.update_cache(line)
1847 1852 #print 'in handle_magic, cmd=<%s>' % cmd # dbg
1848 1853 return cmd
1849 1854
1850 1855 def handle_auto(self, line, continue_prompt=None,
1851 1856 pre=None,iFun=None,theRest=None):
1852 1857 """Hande lines which can be auto-executed, quoting if requested."""
1853 1858
1854 1859 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
1855 1860
1856 1861 # This should only be active for single-line input!
1857 1862 if continue_prompt:
1858 1863 return line
1859 1864
1860 1865 if pre == self.ESC_QUOTE:
1861 1866 # Auto-quote splitting on whitespace
1862 1867 newcmd = '%s("%s")' % (iFun,'", "'.join(theRest.split()) )
1863 1868 elif pre == self.ESC_QUOTE2:
1864 1869 # Auto-quote whole string
1865 1870 newcmd = '%s("%s")' % (iFun,theRest)
1866 1871 else:
1867 1872 # Auto-paren
1868 1873 if theRest[0:1] in ('=','['):
1869 1874 # Don't autocall in these cases. They can be either
1870 1875 # rebindings of an existing callable's name, or item access
1871 1876 # for an object which is BOTH callable and implements
1872 1877 # __getitem__.
1873 1878 return '%s %s' % (iFun,theRest)
1874 1879 if theRest.endswith(';'):
1875 1880 newcmd = '%s(%s);' % (iFun.rstrip(),theRest[:-1])
1876 1881 else:
1877 1882 newcmd = '%s(%s)' % (iFun.rstrip(),theRest)
1878 1883
1879 1884 print >>Term.cout, self.outputcache.prompt1.auto_rewrite() + newcmd
1880 1885 # log what is now valid Python, not the actual user input (without the
1881 1886 # final newline)
1882 1887 self.log(newcmd,continue_prompt)
1883 1888 return newcmd
1884 1889
1885 1890 def handle_help(self, line, continue_prompt=None,
1886 1891 pre=None,iFun=None,theRest=None):
1887 1892 """Try to get some help for the object.
1888 1893
1889 1894 obj? or ?obj -> basic information.
1890 1895 obj?? or ??obj -> more details.
1891 1896 """
1892 1897
1893 1898 # We need to make sure that we don't process lines which would be
1894 1899 # otherwise valid python, such as "x=1 # what?"
1895 1900 try:
1896 1901 codeop.compile_command(line)
1897 1902 except SyntaxError:
1898 1903 # We should only handle as help stuff which is NOT valid syntax
1899 1904 if line[0]==self.ESC_HELP:
1900 1905 line = line[1:]
1901 1906 elif line[-1]==self.ESC_HELP:
1902 1907 line = line[:-1]
1903 1908 self.log('#?'+line)
1904 1909 self.update_cache(line)
1905 1910 if line:
1906 1911 self.magic_pinfo(line)
1907 1912 else:
1908 1913 page(self.usage,screen_lines=self.rc.screen_length)
1909 1914 return '' # Empty string is needed here!
1910 1915 except:
1911 1916 # Pass any other exceptions through to the normal handler
1912 1917 return self.handle_normal(line,continue_prompt)
1913 1918 else:
1914 1919 # If the code compiles ok, we should handle it normally
1915 1920 return self.handle_normal(line,continue_prompt)
1916 1921
1917 1922 def handle_emacs(self,line,continue_prompt=None,
1918 1923 pre=None,iFun=None,theRest=None):
1919 1924 """Handle input lines marked by python-mode."""
1920 1925
1921 1926 # Currently, nothing is done. Later more functionality can be added
1922 1927 # here if needed.
1923 1928
1924 1929 # The input cache shouldn't be updated
1925 1930
1926 1931 return line
1927 1932
1928 1933 def write(self,data):
1929 1934 """Write a string to the default output"""
1930 1935 Term.cout.write(data)
1931 1936
1932 1937 def write_err(self,data):
1933 1938 """Write a string to the default error output"""
1934 1939 Term.cerr.write(data)
1935 1940
1936 1941 def exit(self):
1937 1942 """Handle interactive exit.
1938 1943
1939 1944 This method sets the exit_now attribute."""
1940 1945
1941 1946 if self.rc.confirm_exit:
1942 1947 if ask_yes_no('Do you really want to exit ([y]/n)?','y'):
1943 1948 self.exit_now = True
1944 1949 else:
1945 1950 self.exit_now = True
1946 1951 return self.exit_now
1947 1952
1948 1953 def safe_execfile(self,fname,*where,**kw):
1949 1954 fname = os.path.expanduser(fname)
1950 1955
1951 1956 # find things also in current directory
1952 1957 dname = os.path.dirname(fname)
1953 1958 if not sys.path.count(dname):
1954 1959 sys.path.append(dname)
1955 1960
1956 1961 try:
1957 1962 xfile = open(fname)
1958 1963 except:
1959 1964 print >> Term.cerr, \
1960 1965 'Could not open file <%s> for safe execution.' % fname
1961 1966 return None
1962 1967
1963 1968 kw.setdefault('islog',0)
1964 1969 kw.setdefault('quiet',1)
1965 1970 kw.setdefault('exit_ignore',0)
1966 1971 first = xfile.readline()
1967 1972 loghead = str(self.loghead_tpl).split('\n',1)[0].strip()
1968 1973 xfile.close()
1969 1974 # line by line execution
1970 1975 if first.startswith(loghead) or kw['islog']:
1971 1976 print 'Loading log file <%s> one line at a time...' % fname
1972 1977 if kw['quiet']:
1973 1978 stdout_save = sys.stdout
1974 1979 sys.stdout = StringIO.StringIO()
1975 1980 try:
1976 1981 globs,locs = where[0:2]
1977 1982 except:
1978 1983 try:
1979 1984 globs = locs = where[0]
1980 1985 except:
1981 1986 globs = locs = globals()
1982 1987 badblocks = []
1983 1988
1984 1989 # we also need to identify indented blocks of code when replaying
1985 1990 # logs and put them together before passing them to an exec
1986 1991 # statement. This takes a bit of regexp and look-ahead work in the
1987 1992 # file. It's easiest if we swallow the whole thing in memory
1988 1993 # first, and manually walk through the lines list moving the
1989 1994 # counter ourselves.
1990 1995 indent_re = re.compile('\s+\S')
1991 1996 xfile = open(fname)
1992 1997 filelines = xfile.readlines()
1993 1998 xfile.close()
1994 1999 nlines = len(filelines)
1995 2000 lnum = 0
1996 2001 while lnum < nlines:
1997 2002 line = filelines[lnum]
1998 2003 lnum += 1
1999 2004 # don't re-insert logger status info into cache
2000 2005 if line.startswith('#log#'):
2001 2006 continue
2002 2007 elif line.startswith('#!'):
2003 2008 self.update_cache(line[1:])
2004 2009 else:
2005 2010 # build a block of code (maybe a single line) for execution
2006 2011 block = line
2007 2012 try:
2008 2013 next = filelines[lnum] # lnum has already incremented
2009 2014 except:
2010 2015 next = None
2011 2016 while next and indent_re.match(next):
2012 2017 block += next
2013 2018 lnum += 1
2014 2019 try:
2015 2020 next = filelines[lnum]
2016 2021 except:
2017 2022 next = None
2018 2023 # now execute the block of one or more lines
2019 2024 try:
2020 2025 exec block in globs,locs
2021 2026 self.update_cache(block.rstrip())
2022 2027 except SystemExit:
2023 2028 pass
2024 2029 except:
2025 2030 badblocks.append(block.rstrip())
2026 2031 if kw['quiet']: # restore stdout
2027 2032 sys.stdout.close()
2028 2033 sys.stdout = stdout_save
2029 2034 print 'Finished replaying log file <%s>' % fname
2030 2035 if badblocks:
2031 2036 print >> sys.stderr, ('\nThe following lines/blocks in file '
2032 2037 '<%s> reported errors:' % fname)
2033 2038
2034 2039 for badline in badblocks:
2035 2040 print >> sys.stderr, badline
2036 2041 else: # regular file execution
2037 2042 try:
2038 2043 execfile(fname,*where)
2039 2044 except SyntaxError:
2040 2045 etype,evalue = sys.exc_info()[:2]
2041 2046 self.SyntaxTB(etype,evalue,[])
2042 2047 warn('Failure executing file: <%s>' % fname)
2043 2048 except SystemExit,status:
2044 2049 if not kw['exit_ignore']:
2045 2050 self.InteractiveTB()
2046 2051 warn('Failure executing file: <%s>' % fname)
2047 2052 except:
2048 2053 self.InteractiveTB()
2049 2054 warn('Failure executing file: <%s>' % fname)
2050 2055
2051 2056 #************************* end of file <iplib.py> *****************************
@@ -1,796 +1,796 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 $Id: ultraTB.py 965 2005-12-28 23:23:09Z fperez $"""
63 $Id: ultraTB.py 975 2005-12-29 23:50:22Z fperez $"""
64 64
65 65 #*****************************************************************************
66 66 # Copyright (C) 2001 Nathaniel Gray <n8gray@caltech.edu>
67 67 # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu>
68 68 #
69 69 # Distributed under the terms of the BSD License. The full license is in
70 70 # the file COPYING, distributed as part of this software.
71 71 #*****************************************************************************
72 72
73 73 from IPython import Release
74 74 __author__ = '%s <%s>\n%s <%s>' % (Release.authors['Nathan']+
75 75 Release.authors['Fernando'])
76 76 __license__ = Release.license
77 77
78 78 # Required modules
79 79 import inspect
80 80 import keyword
81 81 import linecache
82 82 import os
83 83 import pydoc
84 84 import string
85 85 import sys
86 86 import time
87 87 import tokenize
88 88 import traceback
89 89 import types
90 90
91 91 # IPython's own modules
92 92 # Modified pdb which doesn't damage IPython's readline handling
93 93 from IPython import Debugger
94 94 from IPython.Struct import Struct
95 95 from IPython.excolors import ExceptionColors
96 96 from IPython.genutils import Term,uniq_stable,error,info
97 97
98 98 #---------------------------------------------------------------------------
99 99 # Code begins
100 100
101 101 def inspect_error():
102 102 """Print a message about internal inspect errors.
103 103
104 104 These are unfortunately quite common."""
105 105
106 106 error('Internal Python error in the inspect module.\n'
107 107 'Below is the traceback from this internal error.\n')
108 108
109 109 class TBTools:
110 110 """Basic tools used by all traceback printer classes."""
111 111
112 112 def __init__(self,color_scheme = 'NoColor',call_pdb=False):
113 113 # Whether to call the interactive pdb debugger after printing
114 114 # tracebacks or not
115 115 self.call_pdb = call_pdb
116 116
117 117 # Create color table
118 118 self.color_scheme_table = ExceptionColors
119 119
120 120 self.set_colors(color_scheme)
121 121 self.old_scheme = color_scheme # save initial value for toggles
122 122
123 123 if call_pdb:
124 124 self.pdb = Debugger.Pdb(self.color_scheme_table.active_scheme_name)
125 125 else:
126 126 self.pdb = None
127 127
128 128 def set_colors(self,*args,**kw):
129 129 """Shorthand access to the color table scheme selector method."""
130 130
131 131 self.color_scheme_table.set_active_scheme(*args,**kw)
132 132 # for convenience, set Colors to the active scheme
133 133 self.Colors = self.color_scheme_table.active_colors
134 134
135 135 def color_toggle(self):
136 136 """Toggle between the currently active color scheme and NoColor."""
137 137
138 138 if self.color_scheme_table.active_scheme_name == 'NoColor':
139 139 self.color_scheme_table.set_active_scheme(self.old_scheme)
140 140 self.Colors = self.color_scheme_table.active_colors
141 141 else:
142 142 self.old_scheme = self.color_scheme_table.active_scheme_name
143 143 self.color_scheme_table.set_active_scheme('NoColor')
144 144 self.Colors = self.color_scheme_table.active_colors
145 145
146 146 #---------------------------------------------------------------------------
147 147 class ListTB(TBTools):
148 148 """Print traceback information from a traceback list, with optional color.
149 149
150 150 Calling: requires 3 arguments:
151 151 (etype, evalue, elist)
152 152 as would be obtained by:
153 153 etype, evalue, tb = sys.exc_info()
154 154 if tb:
155 155 elist = traceback.extract_tb(tb)
156 156 else:
157 157 elist = None
158 158
159 159 It can thus be used by programs which need to process the traceback before
160 160 printing (such as console replacements based on the code module from the
161 161 standard library).
162 162
163 163 Because they are meant to be called without a full traceback (only a
164 164 list), instances of this class can't call the interactive pdb debugger."""
165 165
166 166 def __init__(self,color_scheme = 'NoColor'):
167 167 TBTools.__init__(self,color_scheme = color_scheme,call_pdb=0)
168 168
169 169 def __call__(self, etype, value, elist):
170 170 print >> Term.cerr, self.text(etype,value,elist)
171 171
172 172 def text(self,etype, value, elist,context=5):
173 173 """Return a color formatted string with the traceback info."""
174 174
175 175 Colors = self.Colors
176 176 out_string = ['%s%s%s\n' % (Colors.topline,'-'*60,Colors.Normal)]
177 177 if elist:
178 178 out_string.append('Traceback %s(most recent call last)%s:' % \
179 179 (Colors.normalEm, Colors.Normal) + '\n')
180 180 out_string.extend(self._format_list(elist))
181 181 lines = self._format_exception_only(etype, value)
182 182 for line in lines[:-1]:
183 183 out_string.append(" "+line)
184 184 out_string.append(lines[-1])
185 185 return ''.join(out_string)
186 186
187 187 def _format_list(self, extracted_list):
188 188 """Format a list of traceback entry tuples for printing.
189 189
190 190 Given a list of tuples as returned by extract_tb() or
191 191 extract_stack(), return a list of strings ready for printing.
192 192 Each string in the resulting list corresponds to the item with the
193 193 same index in the argument list. Each string ends in a newline;
194 194 the strings may contain internal newlines as well, for those items
195 195 whose source text line is not None.
196 196
197 197 Lifted almost verbatim from traceback.py
198 198 """
199 199
200 200 Colors = self.Colors
201 201 list = []
202 202 for filename, lineno, name, line in extracted_list[:-1]:
203 203 item = ' File %s"%s"%s, line %s%d%s, in %s%s%s\n' % \
204 204 (Colors.filename, filename, Colors.Normal,
205 205 Colors.lineno, lineno, Colors.Normal,
206 206 Colors.name, name, Colors.Normal)
207 207 if line:
208 208 item = item + ' %s\n' % line.strip()
209 209 list.append(item)
210 210 # Emphasize the last entry
211 211 filename, lineno, name, line = extracted_list[-1]
212 212 item = '%s File %s"%s"%s, line %s%d%s, in %s%s%s%s\n' % \
213 213 (Colors.normalEm,
214 214 Colors.filenameEm, filename, Colors.normalEm,
215 215 Colors.linenoEm, lineno, Colors.normalEm,
216 216 Colors.nameEm, name, Colors.normalEm,
217 217 Colors.Normal)
218 218 if line:
219 219 item = item + '%s %s%s\n' % (Colors.line, line.strip(),
220 220 Colors.Normal)
221 221 list.append(item)
222 222 return list
223 223
224 224 def _format_exception_only(self, etype, value):
225 225 """Format the exception part of a traceback.
226 226
227 227 The arguments are the exception type and value such as given by
228 sys.last_type and sys.last_value. The return value is a list of
229 strings, each ending in a newline. Normally, the list contains a
230 single string; however, for SyntaxError exceptions, it contains
231 several lines that (when printed) display detailed information
232 about where the syntax error occurred. The message indicating
233 which exception occurred is the always last string in the list.
228 sys.exc_info()[:2]. The return value is a list of strings, each ending
229 in a newline. Normally, the list contains a single string; however,
230 for SyntaxError exceptions, it contains several lines that (when
231 printed) display detailed information about where the syntax error
232 occurred. The message indicating which exception occurred is the
233 always last string in the list.
234 234
235 235 Also lifted nearly verbatim from traceback.py
236 236 """
237 237
238 238 Colors = self.Colors
239 239 list = []
240 240 if type(etype) == types.ClassType:
241 241 stype = Colors.excName + etype.__name__ + Colors.Normal
242 242 else:
243 243 stype = etype # String exceptions don't get special coloring
244 244 if value is None:
245 245 list.append( str(stype) + '\n')
246 246 else:
247 247 if etype is SyntaxError:
248 248 try:
249 249 msg, (filename, lineno, offset, line) = value
250 250 except:
251 251 pass
252 252 else:
253 253 #print 'filename is',filename # dbg
254 254 if not filename: filename = "<string>"
255 255 list.append('%s File %s"%s"%s, line %s%d%s\n' % \
256 256 (Colors.normalEm,
257 257 Colors.filenameEm, filename, Colors.normalEm,
258 258 Colors.linenoEm, lineno, Colors.Normal ))
259 259 if line is not None:
260 260 i = 0
261 261 while i < len(line) and line[i].isspace():
262 262 i = i+1
263 263 list.append('%s %s%s\n' % (Colors.line,
264 264 line.strip(),
265 265 Colors.Normal))
266 266 if offset is not None:
267 267 s = ' '
268 268 for c in line[i:offset-1]:
269 269 if c.isspace():
270 270 s = s + c
271 271 else:
272 272 s = s + ' '
273 273 list.append('%s%s^%s\n' % (Colors.caret, s,
274 274 Colors.Normal) )
275 275 value = msg
276 276 s = self._some_str(value)
277 277 if s:
278 278 list.append('%s%s:%s %s\n' % (str(stype), Colors.excName,
279 279 Colors.Normal, s))
280 280 else:
281 281 list.append('%s\n' % str(stype))
282 282 return list
283 283
284 284 def _some_str(self, value):
285 285 # Lifted from traceback.py
286 286 try:
287 287 return str(value)
288 288 except:
289 289 return '<unprintable %s object>' % type(value).__name__
290 290
291 291 #----------------------------------------------------------------------------
292 292 class VerboseTB(TBTools):
293 293 """A port of Ka-Ping Yee's cgitb.py module that outputs color text instead
294 294 of HTML. Requires inspect and pydoc. Crazy, man.
295 295
296 296 Modified version which optionally strips the topmost entries from the
297 297 traceback, to be used with alternate interpreters (because their own code
298 298 would appear in the traceback)."""
299 299
300 300 def __init__(self,color_scheme = 'Linux',tb_offset=0,long_header=0,
301 301 call_pdb = 0, include_vars=1):
302 302 """Specify traceback offset, headers and color scheme.
303 303
304 304 Define how many frames to drop from the tracebacks. Calling it with
305 305 tb_offset=1 allows use of this handler in interpreters which will have
306 306 their own code at the top of the traceback (VerboseTB will first
307 307 remove that frame before printing the traceback info)."""
308 308 TBTools.__init__(self,color_scheme=color_scheme,call_pdb=call_pdb)
309 309 self.tb_offset = tb_offset
310 310 self.long_header = long_header
311 311 self.include_vars = include_vars
312 312
313 313 def text(self, etype, evalue, etb, context=5):
314 314 """Return a nice text document describing the traceback."""
315 315
316 316 # some locals
317 317 Colors = self.Colors # just a shorthand + quicker name lookup
318 318 ColorsNormal = Colors.Normal # used a lot
319 319 indent_size = 8 # we need some space to put line numbers before
320 320 indent = ' '*indent_size
321 321 numbers_width = indent_size - 1 # leave space between numbers & code
322 322 text_repr = pydoc.text.repr
323 323 exc = '%s%s%s' % (Colors.excName, str(etype), ColorsNormal)
324 324 em_normal = '%s\n%s%s' % (Colors.valEm, indent,ColorsNormal)
325 325 undefined = '%sundefined%s' % (Colors.em, ColorsNormal)
326 326
327 327 # some internal-use functions
328 328 def eqrepr(value, repr=text_repr): return '=%s' % repr(value)
329 329 def nullrepr(value, repr=text_repr): return ''
330 330
331 331 # meat of the code begins
332 332 if type(etype) is types.ClassType:
333 333 etype = etype.__name__
334 334
335 335 if self.long_header:
336 336 # Header with the exception type, python version, and date
337 337 pyver = 'Python ' + string.split(sys.version)[0] + ': ' + sys.executable
338 338 date = time.ctime(time.time())
339 339
340 340 head = '%s%s%s\n%s%s%s\n%s' % (Colors.topline, '-'*75, ColorsNormal,
341 341 exc, ' '*(75-len(str(etype))-len(pyver)),
342 342 pyver, string.rjust(date, 75) )
343 343 head += "\nA problem occured executing Python code. Here is the sequence of function"\
344 344 "\ncalls leading up to the error, with the most recent (innermost) call last."
345 345 else:
346 346 # Simplified header
347 347 head = '%s%s%s\n%s%s' % (Colors.topline, '-'*75, ColorsNormal,exc,
348 348 string.rjust('Traceback (most recent call last)',
349 349 75 - len(str(etype)) ) )
350 350 frames = []
351 351 # Flush cache before calling inspect. This helps alleviate some of the
352 352 # problems with python 2.3's inspect.py.
353 353 linecache.checkcache()
354 354 # Drop topmost frames if requested
355 355 try:
356 356 records = inspect.getinnerframes(etb, context)[self.tb_offset:]
357 357 except:
358 358
359 359 # FIXME: I've been getting many crash reports from python 2.3
360 360 # users, traceable to inspect.py. If I can find a small test-case
361 361 # to reproduce this, I should either write a better workaround or
362 362 # file a bug report against inspect (if that's the real problem).
363 363 # So far, I haven't been able to find an isolated example to
364 364 # reproduce the problem.
365 365 inspect_error()
366 366 traceback.print_exc(file=Term.cerr)
367 367 info('\nUnfortunately, your original traceback can not be constructed.\n')
368 368 return ''
369 369
370 370 # build some color string templates outside these nested loops
371 371 tpl_link = '%s%%s%s' % (Colors.filenameEm,ColorsNormal)
372 372 tpl_call = 'in %s%%s%s%%s%s' % (Colors.vName, Colors.valEm,
373 373 ColorsNormal)
374 374 tpl_call_fail = 'in %s%%s%s(***failed resolving arguments***)%s' % \
375 375 (Colors.vName, Colors.valEm, ColorsNormal)
376 376 tpl_local_var = '%s%%s%s' % (Colors.vName, ColorsNormal)
377 377 tpl_global_var = '%sglobal%s %s%%s%s' % (Colors.em, ColorsNormal,
378 378 Colors.vName, ColorsNormal)
379 379 tpl_name_val = '%%s %s= %%s%s' % (Colors.valEm, ColorsNormal)
380 380 tpl_line = '%s%%s%s %%s' % (Colors.lineno, ColorsNormal)
381 381 tpl_line_em = '%s%%s%s %%s%s' % (Colors.linenoEm,Colors.line,
382 382 ColorsNormal)
383 383
384 384 # now, loop over all records printing context and info
385 385 abspath = os.path.abspath
386 386 for frame, file, lnum, func, lines, index in records:
387 387 #print '*** record:',file,lnum,func,lines,index # dbg
388 388 try:
389 389 file = file and abspath(file) or '?'
390 390 except OSError:
391 391 # if file is '<console>' or something not in the filesystem,
392 392 # the abspath call will throw an OSError. Just ignore it and
393 393 # keep the original file string.
394 394 pass
395 395 link = tpl_link % file
396 396 try:
397 397 args, varargs, varkw, locals = inspect.getargvalues(frame)
398 398 except:
399 399 # This can happen due to a bug in python2.3. We should be
400 400 # able to remove this try/except when 2.4 becomes a
401 401 # requirement. Bug details at http://python.org/sf/1005466
402 402 inspect_error()
403 403 traceback.print_exc(file=Term.cerr)
404 404 info("\nIPython's exception reporting continues...\n")
405 405
406 406 if func == '?':
407 407 call = ''
408 408 else:
409 409 # Decide whether to include variable details or not
410 410 var_repr = self.include_vars and eqrepr or nullrepr
411 411 try:
412 412 call = tpl_call % (func,inspect.formatargvalues(args,
413 413 varargs, varkw,
414 414 locals,formatvalue=var_repr))
415 415 except KeyError:
416 416 # Very odd crash from inspect.formatargvalues(). The
417 417 # scenario under which it appeared was a call to
418 418 # view(array,scale) in NumTut.view.view(), where scale had
419 419 # been defined as a scalar (it should be a tuple). Somehow
420 420 # inspect messes up resolving the argument list of view()
421 421 # and barfs out. At some point I should dig into this one
422 422 # and file a bug report about it.
423 423 inspect_error()
424 424 traceback.print_exc(file=Term.cerr)
425 425 info("\nIPython's exception reporting continues...\n")
426 426 call = tpl_call_fail % func
427 427
428 428 # Initialize a list of names on the current line, which the
429 429 # tokenizer below will populate.
430 430 names = []
431 431
432 432 def tokeneater(token_type, token, start, end, line):
433 433 """Stateful tokeneater which builds dotted names.
434 434
435 435 The list of names it appends to (from the enclosing scope) can
436 436 contain repeated composite names. This is unavoidable, since
437 437 there is no way to disambguate partial dotted structures until
438 438 the full list is known. The caller is responsible for pruning
439 439 the final list of duplicates before using it."""
440 440
441 441 # build composite names
442 442 if token == '.':
443 443 try:
444 444 names[-1] += '.'
445 445 # store state so the next token is added for x.y.z names
446 446 tokeneater.name_cont = True
447 447 return
448 448 except IndexError:
449 449 pass
450 450 if token_type == tokenize.NAME and token not in keyword.kwlist:
451 451 if tokeneater.name_cont:
452 452 # Dotted names
453 453 names[-1] += token
454 454 tokeneater.name_cont = False
455 455 else:
456 456 # Regular new names. We append everything, the caller
457 457 # will be responsible for pruning the list later. It's
458 458 # very tricky to try to prune as we go, b/c composite
459 459 # names can fool us. The pruning at the end is easy
460 460 # to do (or the caller can print a list with repeated
461 461 # names if so desired.
462 462 names.append(token)
463 463 elif token_type == tokenize.NEWLINE:
464 464 raise IndexError
465 465 # we need to store a bit of state in the tokenizer to build
466 466 # dotted names
467 467 tokeneater.name_cont = False
468 468
469 469 def linereader(file=file, lnum=[lnum], getline=linecache.getline):
470 470 line = getline(file, lnum[0])
471 471 lnum[0] += 1
472 472 return line
473 473
474 474 # Build the list of names on this line of code where the exception
475 475 # occurred.
476 476 try:
477 477 # This builds the names list in-place by capturing it from the
478 478 # enclosing scope.
479 479 tokenize.tokenize(linereader, tokeneater)
480 480 except IndexError:
481 481 # signals exit of tokenizer
482 482 pass
483 483 except tokenize.TokenError,msg:
484 484 _m = ("An unexpected error occurred while tokenizing input\n"
485 485 "The following traceback may be corrupted or invalid\n"
486 486 "The error message is: %s\n" % msg)
487 487 error(_m)
488 488
489 489 # prune names list of duplicates, but keep the right order
490 490 unique_names = uniq_stable(names)
491 491
492 492 # Start loop over vars
493 493 lvals = []
494 494 if self.include_vars:
495 495 for name_full in unique_names:
496 496 name_base = name_full.split('.',1)[0]
497 497 if name_base in frame.f_code.co_varnames:
498 498 if locals.has_key(name_base):
499 499 try:
500 500 value = repr(eval(name_full,locals))
501 501 except:
502 502 value = undefined
503 503 else:
504 504 value = undefined
505 505 name = tpl_local_var % name_full
506 506 else:
507 507 if frame.f_globals.has_key(name_base):
508 508 try:
509 509 value = repr(eval(name_full,frame.f_globals))
510 510 except:
511 511 value = undefined
512 512 else:
513 513 value = undefined
514 514 name = tpl_global_var % name_full
515 515 lvals.append(tpl_name_val % (name,value))
516 516 if lvals:
517 517 lvals = '%s%s' % (indent,em_normal.join(lvals))
518 518 else:
519 519 lvals = ''
520 520
521 521 level = '%s %s\n' % (link,call)
522 522 excerpt = []
523 523 if index is not None:
524 524 i = lnum - index
525 525 for line in lines:
526 526 if i == lnum:
527 527 # This is the line with the error
528 528 pad = numbers_width - len(str(i))
529 529 if pad >= 3:
530 530 marker = '-'*(pad-3) + '-> '
531 531 elif pad == 2:
532 532 marker = '> '
533 533 elif pad == 1:
534 534 marker = '>'
535 535 else:
536 536 marker = ''
537 537 num = '%s%s' % (marker,i)
538 538 line = tpl_line_em % (num,line)
539 539 else:
540 540 num = '%*s' % (numbers_width,i)
541 541 line = tpl_line % (num,line)
542 542
543 543 excerpt.append(line)
544 544 if self.include_vars and i == lnum:
545 545 excerpt.append('%s\n' % lvals)
546 546 i += 1
547 547 frames.append('%s%s' % (level,''.join(excerpt)) )
548 548
549 549 # Get (safely) a string form of the exception info
550 550 try:
551 551 etype_str,evalue_str = map(str,(etype,evalue))
552 552 except:
553 553 # User exception is improperly defined.
554 554 etype,evalue = str,sys.exc_info()[:2]
555 555 etype_str,evalue_str = map(str,(etype,evalue))
556 556 # ... and format it
557 557 exception = ['%s%s%s: %s' % (Colors.excName, etype_str,
558 558 ColorsNormal, evalue_str)]
559 559 if type(evalue) is types.InstanceType:
560 560 try:
561 561 names = [w for w in dir(evalue) if isinstance(w, basestring)]
562 562 except:
563 563 # Every now and then, an object with funny inernals blows up
564 564 # when dir() is called on it. We do the best we can to report
565 565 # the problem and continue
566 566 _m = '%sException reporting error (object with broken dir())%s:'
567 567 exception.append(_m % (Colors.excName,ColorsNormal))
568 568 etype_str,evalue_str = map(str,sys.exc_info()[:2])
569 569 exception.append('%s%s%s: %s' % (Colors.excName,etype_str,
570 570 ColorsNormal, evalue_str))
571 571 names = []
572 572 for name in names:
573 573 value = text_repr(getattr(evalue, name))
574 574 exception.append('\n%s%s = %s' % (indent, name, value))
575 575 # return all our info assembled as a single string
576 576 return '%s\n\n%s\n%s' % (head,'\n'.join(frames),''.join(exception[0]) )
577 577
578 578 def debugger(self):
579 579 """Call up the pdb debugger if desired, always clean up the tb reference.
580 580
581 581 If the call_pdb flag is set, the pdb interactive debugger is
582 582 invoked. In all cases, the self.tb reference to the current traceback
583 583 is deleted to prevent lingering references which hamper memory
584 584 management.
585 585
586 586 Note that each call to pdb() does an 'import readline', so if your app
587 587 requires a special setup for the readline completers, you'll have to
588 588 fix that by hand after invoking the exception handler."""
589 589
590 590 if self.call_pdb:
591 591 if self.pdb is None:
592 592 self.pdb = Debugger.Pdb(
593 593 self.color_scheme_table.active_scheme_name)
594 594 # the system displayhook may have changed, restore the original
595 595 # for pdb
596 596 dhook = sys.displayhook
597 597 sys.displayhook = sys.__displayhook__
598 598 self.pdb.reset()
599 599 # Find the right frame so we don't pop up inside ipython itself
600 600 etb = self.tb
601 601 while self.tb.tb_next is not None:
602 602 self.tb = self.tb.tb_next
603 603 try:
604 604 if etb and etb.tb_next:
605 605 etb = etb.tb_next
606 606 self.pdb.botframe = etb.tb_frame
607 607 self.pdb.interaction(self.tb.tb_frame, self.tb)
608 608 except:
609 609 print '*** ERROR ***'
610 610 print 'This version of pdb has a bug and crashed.'
611 611 print 'Returning to IPython...'
612 612 sys.displayhook = dhook
613 613 del self.tb
614 614
615 615 def handler(self, info=None):
616 616 (etype, evalue, etb) = info or sys.exc_info()
617 617 self.tb = etb
618 618 print >> Term.cerr, self.text(etype, evalue, etb)
619 619
620 620 # Changed so an instance can just be called as VerboseTB_inst() and print
621 621 # out the right info on its own.
622 622 def __call__(self, etype=None, evalue=None, etb=None):
623 623 """This hook can replace sys.excepthook (for Python 2.1 or higher)."""
624 624 if etb is None:
625 625 self.handler()
626 626 else:
627 627 self.handler((etype, evalue, etb))
628 628 self.debugger()
629 629
630 630 #----------------------------------------------------------------------------
631 631 class FormattedTB(VerboseTB,ListTB):
632 632 """Subclass ListTB but allow calling with a traceback.
633 633
634 634 It can thus be used as a sys.excepthook for Python > 2.1.
635 635
636 636 Also adds 'Context' and 'Verbose' modes, not available in ListTB.
637 637
638 638 Allows a tb_offset to be specified. This is useful for situations where
639 639 one needs to remove a number of topmost frames from the traceback (such as
640 640 occurs with python programs that themselves execute other python code,
641 641 like Python shells). """
642 642
643 643 def __init__(self, mode = 'Plain', color_scheme='Linux',
644 644 tb_offset = 0,long_header=0,call_pdb=0,include_vars=0):
645 645
646 646 # NEVER change the order of this list. Put new modes at the end:
647 647 self.valid_modes = ['Plain','Context','Verbose']
648 648 self.verbose_modes = self.valid_modes[1:3]
649 649
650 650 VerboseTB.__init__(self,color_scheme,tb_offset,long_header,
651 651 call_pdb=call_pdb,include_vars=include_vars)
652 652 self.set_mode(mode)
653 653
654 654 def _extract_tb(self,tb):
655 655 if tb:
656 656 return traceback.extract_tb(tb)
657 657 else:
658 658 return None
659 659
660 660 def text(self, etype, value, tb,context=5,mode=None):
661 661 """Return formatted traceback.
662 662
663 663 If the optional mode parameter is given, it overrides the current
664 664 mode."""
665 665
666 666 if mode is None:
667 667 mode = self.mode
668 668 if mode in self.verbose_modes:
669 669 # verbose modes need a full traceback
670 670 return VerboseTB.text(self,etype, value, tb,context=5)
671 671 else:
672 672 # We must check the source cache because otherwise we can print
673 673 # out-of-date source code.
674 674 linecache.checkcache()
675 675 # Now we can extract and format the exception
676 676 elist = self._extract_tb(tb)
677 677 if len(elist) > self.tb_offset:
678 678 del elist[:self.tb_offset]
679 679 return ListTB.text(self,etype,value,elist)
680 680
681 681 def set_mode(self,mode=None):
682 682 """Switch to the desired mode.
683 683
684 684 If mode is not specified, cycles through the available modes."""
685 685
686 686 if not mode:
687 687 new_idx = ( self.valid_modes.index(self.mode) + 1 ) % \
688 688 len(self.valid_modes)
689 689 self.mode = self.valid_modes[new_idx]
690 690 elif mode not in self.valid_modes:
691 691 raise ValueError, 'Unrecognized mode in FormattedTB: <'+mode+'>\n'\
692 692 'Valid modes: '+str(self.valid_modes)
693 693 else:
694 694 self.mode = mode
695 695 # include variable details only in 'Verbose' mode
696 696 self.include_vars = (self.mode == self.valid_modes[2])
697 697
698 698 # some convenient shorcuts
699 699 def plain(self):
700 700 self.set_mode(self.valid_modes[0])
701 701
702 702 def context(self):
703 703 self.set_mode(self.valid_modes[1])
704 704
705 705 def verbose(self):
706 706 self.set_mode(self.valid_modes[2])
707 707
708 708 #----------------------------------------------------------------------------
709 709 class AutoFormattedTB(FormattedTB):
710 710 """A traceback printer which can be called on the fly.
711 711
712 712 It will find out about exceptions by itself.
713 713
714 714 A brief example:
715 715
716 716 AutoTB = AutoFormattedTB(mode = 'Verbose',color_scheme='Linux')
717 717 try:
718 718 ...
719 719 except:
720 720 AutoTB() # or AutoTB(out=logfile) where logfile is an open file object
721 721 """
722 722 def __call__(self,etype=None,evalue=None,etb=None,
723 723 out=None,tb_offset=None):
724 724 """Print out a formatted exception traceback.
725 725
726 726 Optional arguments:
727 727 - out: an open file-like object to direct output to.
728 728
729 729 - tb_offset: the number of frames to skip over in the stack, on a
730 730 per-call basis (this overrides temporarily the instance's tb_offset
731 731 given at initialization time. """
732 732
733 733 if out is None:
734 734 out = Term.cerr
735 735 if tb_offset is not None:
736 736 tb_offset, self.tb_offset = self.tb_offset, tb_offset
737 737 print >> out, self.text(etype, evalue, etb)
738 738 self.tb_offset = tb_offset
739 739 else:
740 740 print >> out, self.text(etype, evalue, etb)
741 741 self.debugger()
742 742
743 743 def text(self,etype=None,value=None,tb=None,context=5,mode=None):
744 744 if etype is None:
745 745 etype,value,tb = sys.exc_info()
746 746 self.tb = tb
747 747 return FormattedTB.text(self,etype,value,tb,context=5,mode=mode)
748 748
749 749 #---------------------------------------------------------------------------
750 750 # A simple class to preserve Nathan's original functionality.
751 751 class ColorTB(FormattedTB):
752 752 """Shorthand to initialize a FormattedTB in Linux colors mode."""
753 753 def __init__(self,color_scheme='Linux',call_pdb=0):
754 754 FormattedTB.__init__(self,color_scheme=color_scheme,
755 755 call_pdb=call_pdb)
756 756
757 757 #----------------------------------------------------------------------------
758 758 # module testing (minimal)
759 759 if __name__ == "__main__":
760 760 def spam(c, (d, e)):
761 761 x = c + d
762 762 y = c * d
763 763 foo(x, y)
764 764
765 765 def foo(a, b, bar=1):
766 766 eggs(a, b + bar)
767 767
768 768 def eggs(f, g, z=globals()):
769 769 h = f + g
770 770 i = f - g
771 771 return h / i
772 772
773 773 print ''
774 774 print '*** Before ***'
775 775 try:
776 776 print spam(1, (2, 3))
777 777 except:
778 778 traceback.print_exc()
779 779 print ''
780 780
781 781 handler = ColorTB()
782 782 print '*** ColorTB ***'
783 783 try:
784 784 print spam(1, (2, 3))
785 785 except:
786 786 apply(handler, sys.exc_info() )
787 787 print ''
788 788
789 789 handler = VerboseTB()
790 790 print '*** VerboseTB ***'
791 791 try:
792 792 print spam(1, (2, 3))
793 793 except:
794 794 apply(handler, sys.exc_info() )
795 795 print ''
796 796
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