##// END OF EJS Templates
Fernando Perez -
Show More
@@ -1,3415 +1,3418 b''
1 1 # -*- coding: utf-8 -*-
2 2 """Magic functions for InteractiveShell.
3 3 """
4 4
5 5 #*****************************************************************************
6 6 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
7 7 # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu>
8 8 #
9 9 # Distributed under the terms of the BSD License. The full license is in
10 10 # the file COPYING, distributed as part of this software.
11 11 #*****************************************************************************
12 12
13 13 #****************************************************************************
14 14 # Modules and globals
15 15
16 from IPython import Release
17 __author__ = '%s <%s>\n%s <%s>' % \
18 ( Release.authors['Janko'] + Release.authors['Fernando'] )
19 __license__ = Release.license
20
21 16 # Python standard modules
22 17 import __builtin__
23 18 import bdb
24 19 import inspect
25 20 import os
26 21 import pdb
27 22 import pydoc
28 23 import sys
29 24 import re
30 25 import tempfile
31 26 import time
32 27 import cPickle as pickle
33 28 import textwrap
34 29 from cStringIO import StringIO
35 30 from getopt import getopt,GetoptError
36 31 from pprint import pprint, pformat
37 32 from sets import Set
38 33
39 34 # cProfile was added in Python2.5
40 35 try:
41 36 import cProfile as profile
42 37 import pstats
43 38 except ImportError:
44 39 # profile isn't bundled by default in Debian for license reasons
45 40 try:
46 41 import profile,pstats
47 42 except ImportError:
48 43 profile = pstats = None
49 44
50 45 # Homebrewed
51 46 import IPython
52 47 from IPython import Debugger, OInspect, wildcard
53 48 from IPython.FakeModule import FakeModule
54 49 from IPython.Itpl import Itpl, itpl, printpl,itplns
55 50 from IPython.PyColorize import Parser
56 51 from IPython.ipstruct import Struct
57 52 from IPython.macro import Macro
58 53 from IPython.genutils import *
59 54 from IPython import platutils
60 55 import IPython.generics
61 56 import IPython.ipapi
62 57 from IPython.ipapi import UsageError
63 58 from IPython.testing import decorators as testdec
64 59
65 60 #***************************************************************************
66 61 # Utility functions
67 62 def on_off(tag):
68 63 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
69 64 return ['OFF','ON'][tag]
70 65
71 66 class Bunch: pass
72 67
73 68 def compress_dhist(dh):
74 69 head, tail = dh[:-10], dh[-10:]
75 70
76 71 newhead = []
77 72 done = Set()
78 73 for h in head:
79 74 if h in done:
80 75 continue
81 76 newhead.append(h)
82 77 done.add(h)
83 78
84 79 return newhead + tail
85 80
86 81
87 82 #***************************************************************************
88 83 # Main class implementing Magic functionality
89 84 class Magic:
90 85 """Magic functions for InteractiveShell.
91 86
92 87 Shell functions which can be reached as %function_name. All magic
93 88 functions should accept a string, which they can parse for their own
94 89 needs. This can make some functions easier to type, eg `%cd ../`
95 90 vs. `%cd("../")`
96 91
97 92 ALL definitions MUST begin with the prefix magic_. The user won't need it
98 93 at the command line, but it is is needed in the definition. """
99 94
100 95 # class globals
101 96 auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.',
102 97 'Automagic is ON, % prefix NOT needed for magic functions.']
103 98
104 99 #......................................................................
105 100 # some utility functions
106 101
107 102 def __init__(self,shell):
108 103
109 104 self.options_table = {}
110 105 if profile is None:
111 106 self.magic_prun = self.profile_missing_notice
112 107 self.shell = shell
113 108
114 109 # namespace for holding state we may need
115 110 self._magic_state = Bunch()
116 111
117 112 def profile_missing_notice(self, *args, **kwargs):
118 113 error("""\
119 114 The profile module could not be found. It has been removed from the standard
120 115 python packages because of its non-free license. To use profiling, install the
121 116 python-profiler package from non-free.""")
122 117
123 118 def default_option(self,fn,optstr):
124 119 """Make an entry in the options_table for fn, with value optstr"""
125 120
126 121 if fn not in self.lsmagic():
127 122 error("%s is not a magic function" % fn)
128 123 self.options_table[fn] = optstr
129 124
130 125 def lsmagic(self):
131 126 """Return a list of currently available magic functions.
132 127
133 128 Gives a list of the bare names after mangling (['ls','cd', ...], not
134 129 ['magic_ls','magic_cd',...]"""
135 130
136 131 # FIXME. This needs a cleanup, in the way the magics list is built.
137 132
138 133 # magics in class definition
139 134 class_magic = lambda fn: fn.startswith('magic_') and \
140 135 callable(Magic.__dict__[fn])
141 136 # in instance namespace (run-time user additions)
142 137 inst_magic = lambda fn: fn.startswith('magic_') and \
143 138 callable(self.__dict__[fn])
144 139 # and bound magics by user (so they can access self):
145 140 inst_bound_magic = lambda fn: fn.startswith('magic_') and \
146 141 callable(self.__class__.__dict__[fn])
147 142 magics = filter(class_magic,Magic.__dict__.keys()) + \
148 143 filter(inst_magic,self.__dict__.keys()) + \
149 144 filter(inst_bound_magic,self.__class__.__dict__.keys())
150 145 out = []
151 146 for fn in Set(magics):
152 147 out.append(fn.replace('magic_','',1))
153 148 out.sort()
154 149 return out
155 150
156 151 def extract_input_slices(self,slices,raw=False):
157 152 """Return as a string a set of input history slices.
158 153
159 154 Inputs:
160 155
161 156 - slices: the set of slices is given as a list of strings (like
162 157 ['1','4:8','9'], since this function is for use by magic functions
163 158 which get their arguments as strings.
164 159
165 160 Optional inputs:
166 161
167 162 - raw(False): by default, the processed input is used. If this is
168 163 true, the raw input history is used instead.
169 164
170 165 Note that slices can be called with two notations:
171 166
172 167 N:M -> standard python form, means including items N...(M-1).
173 168
174 169 N-M -> include items N..M (closed endpoint)."""
175 170
176 171 if raw:
177 172 hist = self.shell.input_hist_raw
178 173 else:
179 174 hist = self.shell.input_hist
180 175
181 176 cmds = []
182 177 for chunk in slices:
183 178 if ':' in chunk:
184 179 ini,fin = map(int,chunk.split(':'))
185 180 elif '-' in chunk:
186 181 ini,fin = map(int,chunk.split('-'))
187 182 fin += 1
188 183 else:
189 184 ini = int(chunk)
190 185 fin = ini+1
191 186 cmds.append(hist[ini:fin])
192 187 return cmds
193 188
194 189 def _ofind(self, oname, namespaces=None):
195 190 """Find an object in the available namespaces.
196 191
197 192 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
198 193
199 194 Has special code to detect magic functions.
200 195 """
201 196
202 197 oname = oname.strip()
203 198
204 199 alias_ns = None
205 200 if namespaces is None:
206 201 # Namespaces to search in:
207 202 # Put them in a list. The order is important so that we
208 203 # find things in the same order that Python finds them.
209 204 namespaces = [ ('Interactive', self.shell.user_ns),
210 205 ('IPython internal', self.shell.internal_ns),
211 206 ('Python builtin', __builtin__.__dict__),
212 207 ('Alias', self.shell.alias_table),
213 208 ]
214 209 alias_ns = self.shell.alias_table
215 210
216 211 # initialize results to 'null'
217 212 found = 0; obj = None; ospace = None; ds = None;
218 213 ismagic = 0; isalias = 0; parent = None
219 214
220 215 # Look for the given name by splitting it in parts. If the head is
221 216 # found, then we look for all the remaining parts as members, and only
222 217 # declare success if we can find them all.
223 218 oname_parts = oname.split('.')
224 219 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
225 220 for nsname,ns in namespaces:
226 221 try:
227 222 obj = ns[oname_head]
228 223 except KeyError:
229 224 continue
230 225 else:
231 226 #print 'oname_rest:', oname_rest # dbg
232 227 for part in oname_rest:
233 228 try:
234 229 parent = obj
235 230 obj = getattr(obj,part)
236 231 except:
237 232 # Blanket except b/c some badly implemented objects
238 233 # allow __getattr__ to raise exceptions other than
239 234 # AttributeError, which then crashes IPython.
240 235 break
241 236 else:
242 237 # If we finish the for loop (no break), we got all members
243 238 found = 1
244 239 ospace = nsname
245 240 if ns == alias_ns:
246 241 isalias = 1
247 242 break # namespace loop
248 243
249 244 # Try to see if it's magic
250 245 if not found:
251 246 if oname.startswith(self.shell.ESC_MAGIC):
252 247 oname = oname[1:]
253 248 obj = getattr(self,'magic_'+oname,None)
254 249 if obj is not None:
255 250 found = 1
256 251 ospace = 'IPython internal'
257 252 ismagic = 1
258 253
259 254 # Last try: special-case some literals like '', [], {}, etc:
260 255 if not found and oname_head in ["''",'""','[]','{}','()']:
261 256 obj = eval(oname_head)
262 257 found = 1
263 258 ospace = 'Interactive'
264 259
265 260 return {'found':found, 'obj':obj, 'namespace':ospace,
266 261 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
267 262
268 263 def arg_err(self,func):
269 264 """Print docstring if incorrect arguments were passed"""
270 265 print 'Error in arguments:'
271 266 print OInspect.getdoc(func)
272 267
273 268 def format_latex(self,strng):
274 269 """Format a string for latex inclusion."""
275 270
276 271 # Characters that need to be escaped for latex:
277 272 escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE)
278 273 # Magic command names as headers:
279 274 cmd_name_re = re.compile(r'^(%s.*?):' % self.shell.ESC_MAGIC,
280 275 re.MULTILINE)
281 276 # Magic commands
282 277 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % self.shell.ESC_MAGIC,
283 278 re.MULTILINE)
284 279 # Paragraph continue
285 280 par_re = re.compile(r'\\$',re.MULTILINE)
286 281
287 282 # The "\n" symbol
288 283 newline_re = re.compile(r'\\n')
289 284
290 285 # Now build the string for output:
291 286 #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
292 287 strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
293 288 strng)
294 289 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
295 290 strng = par_re.sub(r'\\\\',strng)
296 291 strng = escape_re.sub(r'\\\1',strng)
297 292 strng = newline_re.sub(r'\\textbackslash{}n',strng)
298 293 return strng
299 294
300 295 def format_screen(self,strng):
301 296 """Format a string for screen printing.
302 297
303 298 This removes some latex-type format codes."""
304 299 # Paragraph continue
305 300 par_re = re.compile(r'\\$',re.MULTILINE)
306 301 strng = par_re.sub('',strng)
307 302 return strng
308 303
309 304 def parse_options(self,arg_str,opt_str,*long_opts,**kw):
310 305 """Parse options passed to an argument string.
311 306
312 307 The interface is similar to that of getopt(), but it returns back a
313 308 Struct with the options as keys and the stripped argument string still
314 309 as a string.
315 310
316 311 arg_str is quoted as a true sys.argv vector by using shlex.split.
317 312 This allows us to easily expand variables, glob files, quote
318 313 arguments, etc.
319 314
320 315 Options:
321 316 -mode: default 'string'. If given as 'list', the argument string is
322 317 returned as a list (split on whitespace) instead of a string.
323 318
324 319 -list_all: put all option values in lists. Normally only options
325 320 appearing more than once are put in a list.
326 321
327 322 -posix (True): whether to split the input line in POSIX mode or not,
328 323 as per the conventions outlined in the shlex module from the
329 324 standard library."""
330 325
331 326 # inject default options at the beginning of the input line
332 327 caller = sys._getframe(1).f_code.co_name.replace('magic_','')
333 328 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
334 329
335 330 mode = kw.get('mode','string')
336 331 if mode not in ['string','list']:
337 332 raise ValueError,'incorrect mode given: %s' % mode
338 333 # Get options
339 334 list_all = kw.get('list_all',0)
340 335 posix = kw.get('posix',True)
341 336
342 337 # Check if we have more than one argument to warrant extra processing:
343 338 odict = {} # Dictionary with options
344 339 args = arg_str.split()
345 340 if len(args) >= 1:
346 341 # If the list of inputs only has 0 or 1 thing in it, there's no
347 342 # need to look for options
348 343 argv = arg_split(arg_str,posix)
349 344 # Do regular option processing
350 345 try:
351 346 opts,args = getopt(argv,opt_str,*long_opts)
352 347 except GetoptError,e:
353 348 raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str,
354 349 " ".join(long_opts)))
355 350 for o,a in opts:
356 351 if o.startswith('--'):
357 352 o = o[2:]
358 353 else:
359 354 o = o[1:]
360 355 try:
361 356 odict[o].append(a)
362 357 except AttributeError:
363 358 odict[o] = [odict[o],a]
364 359 except KeyError:
365 360 if list_all:
366 361 odict[o] = [a]
367 362 else:
368 363 odict[o] = a
369 364
370 365 # Prepare opts,args for return
371 366 opts = Struct(odict)
372 367 if mode == 'string':
373 368 args = ' '.join(args)
374 369
375 370 return opts,args
376 371
377 372 #......................................................................
378 373 # And now the actual magic functions
379 374
380 375 # Functions for IPython shell work (vars,funcs, config, etc)
381 376 def magic_lsmagic(self, parameter_s = ''):
382 377 """List currently available magic functions."""
383 378 mesc = self.shell.ESC_MAGIC
384 379 print 'Available magic functions:\n'+mesc+\
385 380 (' '+mesc).join(self.lsmagic())
386 381 print '\n' + Magic.auto_status[self.shell.rc.automagic]
387 382 return None
388 383
389 384 def magic_magic(self, parameter_s = ''):
390 385 """Print information about the magic function system.
391 386
392 387 Supported formats: -latex, -brief, -rest
393 388 """
394 389
395 390 mode = ''
396 391 try:
397 392 if parameter_s.split()[0] == '-latex':
398 393 mode = 'latex'
399 394 if parameter_s.split()[0] == '-brief':
400 395 mode = 'brief'
401 396 if parameter_s.split()[0] == '-rest':
402 397 mode = 'rest'
403 398 rest_docs = []
404 399 except:
405 400 pass
406 401
407 402 magic_docs = []
408 403 for fname in self.lsmagic():
409 404 mname = 'magic_' + fname
410 405 for space in (Magic,self,self.__class__):
411 406 try:
412 407 fn = space.__dict__[mname]
413 408 except KeyError:
414 409 pass
415 410 else:
416 411 break
417 412 if mode == 'brief':
418 413 # only first line
419 414 if fn.__doc__:
420 415 fndoc = fn.__doc__.split('\n',1)[0]
421 416 else:
422 417 fndoc = 'No documentation'
423 418 else:
424 419 fndoc = fn.__doc__.rstrip()
425 420
426 421 if mode == 'rest':
427 422 rest_docs.append('**%s%s**::\n\n\t%s\n\n' %(self.shell.ESC_MAGIC,
428 423 fname,fndoc))
429 424
430 425 else:
431 426 magic_docs.append('%s%s:\n\t%s\n' %(self.shell.ESC_MAGIC,
432 427 fname,fndoc))
433 428
434 429 magic_docs = ''.join(magic_docs)
435 430
436 431 if mode == 'rest':
437 432 return "".join(rest_docs)
438 433
439 434 if mode == 'latex':
440 435 print self.format_latex(magic_docs)
441 436 return
442 437 else:
443 438 magic_docs = self.format_screen(magic_docs)
444 439 if mode == 'brief':
445 440 return magic_docs
446 441
447 442 outmsg = """
448 443 IPython's 'magic' functions
449 444 ===========================
450 445
451 446 The magic function system provides a series of functions which allow you to
452 447 control the behavior of IPython itself, plus a lot of system-type
453 448 features. All these functions are prefixed with a % character, but parameters
454 449 are given without parentheses or quotes.
455 450
456 451 NOTE: If you have 'automagic' enabled (via the command line option or with the
457 452 %automagic function), you don't need to type in the % explicitly. By default,
458 453 IPython ships with automagic on, so you should only rarely need the % escape.
459 454
460 455 Example: typing '%cd mydir' (without the quotes) changes you working directory
461 456 to 'mydir', if it exists.
462 457
463 458 You can define your own magic functions to extend the system. See the supplied
464 459 ipythonrc and example-magic.py files for details (in your ipython
465 460 configuration directory, typically $HOME/.ipython/).
466 461
467 462 You can also define your own aliased names for magic functions. In your
468 463 ipythonrc file, placing a line like:
469 464
470 465 execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
471 466
472 467 will define %pf as a new name for %profile.
473 468
474 469 You can also call magics in code using the ipmagic() function, which IPython
475 470 automatically adds to the builtin namespace. Type 'ipmagic?' for details.
476 471
477 472 For a list of the available magic functions, use %lsmagic. For a description
478 473 of any of them, type %magic_name?, e.g. '%cd?'.
479 474
480 475 Currently the magic system has the following functions:\n"""
481 476
482 477 mesc = self.shell.ESC_MAGIC
483 478 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
484 479 "\n\n%s%s\n\n%s" % (outmsg,
485 480 magic_docs,mesc,mesc,
486 481 (' '+mesc).join(self.lsmagic()),
487 482 Magic.auto_status[self.shell.rc.automagic] ) )
488 483
489 484 page(outmsg,screen_lines=self.shell.rc.screen_length)
490 485
491 486
492 487 def magic_autoindent(self, parameter_s = ''):
493 488 """Toggle autoindent on/off (if available)."""
494 489
495 490 self.shell.set_autoindent()
496 491 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
497 492
498 493
499 494 def magic_automagic(self, parameter_s = ''):
500 495 """Make magic functions callable without having to type the initial %.
501 496
502 497 Without argumentsl toggles on/off (when off, you must call it as
503 498 %automagic, of course). With arguments it sets the value, and you can
504 499 use any of (case insensitive):
505 500
506 501 - on,1,True: to activate
507 502
508 503 - off,0,False: to deactivate.
509 504
510 505 Note that magic functions have lowest priority, so if there's a
511 506 variable whose name collides with that of a magic fn, automagic won't
512 507 work for that function (you get the variable instead). However, if you
513 508 delete the variable (del var), the previously shadowed magic function
514 509 becomes visible to automagic again."""
515 510
516 511 rc = self.shell.rc
517 512 arg = parameter_s.lower()
518 513 if parameter_s in ('on','1','true'):
519 514 rc.automagic = True
520 515 elif parameter_s in ('off','0','false'):
521 516 rc.automagic = False
522 517 else:
523 518 rc.automagic = not rc.automagic
524 519 print '\n' + Magic.auto_status[rc.automagic]
525 520
526 521 @testdec.skip_doctest
527 522 def magic_autocall(self, parameter_s = ''):
528 523 """Make functions callable without having to type parentheses.
529 524
530 525 Usage:
531 526
532 527 %autocall [mode]
533 528
534 529 The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the
535 530 value is toggled on and off (remembering the previous state).
536 531
537 532 In more detail, these values mean:
538 533
539 534 0 -> fully disabled
540 535
541 536 1 -> active, but do not apply if there are no arguments on the line.
542 537
543 538 In this mode, you get:
544 539
545 540 In [1]: callable
546 541 Out[1]: <built-in function callable>
547 542
548 543 In [2]: callable 'hello'
549 544 ------> callable('hello')
550 545 Out[2]: False
551 546
552 547 2 -> Active always. Even if no arguments are present, the callable
553 548 object is called:
554 549
555 550 In [2]: float
556 551 ------> float()
557 552 Out[2]: 0.0
558 553
559 554 Note that even with autocall off, you can still use '/' at the start of
560 555 a line to treat the first argument on the command line as a function
561 556 and add parentheses to it:
562 557
563 558 In [8]: /str 43
564 559 ------> str(43)
565 560 Out[8]: '43'
566 561
567 562 # all-random (note for auto-testing)
568 563 """
569 564
570 565 rc = self.shell.rc
571 566
572 567 if parameter_s:
573 568 arg = int(parameter_s)
574 569 else:
575 570 arg = 'toggle'
576 571
577 572 if not arg in (0,1,2,'toggle'):
578 573 error('Valid modes: (0->Off, 1->Smart, 2->Full')
579 574 return
580 575
581 576 if arg in (0,1,2):
582 577 rc.autocall = arg
583 578 else: # toggle
584 579 if rc.autocall:
585 580 self._magic_state.autocall_save = rc.autocall
586 581 rc.autocall = 0
587 582 else:
588 583 try:
589 584 rc.autocall = self._magic_state.autocall_save
590 585 except AttributeError:
591 586 rc.autocall = self._magic_state.autocall_save = 1
592 587
593 588 print "Automatic calling is:",['OFF','Smart','Full'][rc.autocall]
594 589
595 590 def magic_system_verbose(self, parameter_s = ''):
596 591 """Set verbose printing of system calls.
597 592
598 593 If called without an argument, act as a toggle"""
599 594
600 595 if parameter_s:
601 596 val = bool(eval(parameter_s))
602 597 else:
603 598 val = None
604 599
605 600 self.shell.rc_set_toggle('system_verbose',val)
606 601 print "System verbose printing is:",\
607 602 ['OFF','ON'][self.shell.rc.system_verbose]
608 603
609 604
610 605 def magic_page(self, parameter_s=''):
611 606 """Pretty print the object and display it through a pager.
612 607
613 608 %page [options] OBJECT
614 609
615 610 If no object is given, use _ (last output).
616 611
617 612 Options:
618 613
619 614 -r: page str(object), don't pretty-print it."""
620 615
621 616 # After a function contributed by Olivier Aubert, slightly modified.
622 617
623 618 # Process options/args
624 619 opts,args = self.parse_options(parameter_s,'r')
625 620 raw = 'r' in opts
626 621
627 622 oname = args and args or '_'
628 623 info = self._ofind(oname)
629 624 if info['found']:
630 625 txt = (raw and str or pformat)( info['obj'] )
631 626 page(txt)
632 627 else:
633 628 print 'Object `%s` not found' % oname
634 629
635 630 def magic_profile(self, parameter_s=''):
636 631 """Print your currently active IPyhton profile."""
637 632 if self.shell.rc.profile:
638 633 printpl('Current IPython profile: $self.shell.rc.profile.')
639 634 else:
640 635 print 'No profile active.'
641 636
642 637 def magic_pinfo(self, parameter_s='', namespaces=None):
643 638 """Provide detailed information about an object.
644 639
645 640 '%pinfo object' is just a synonym for object? or ?object."""
646 641
647 642 #print 'pinfo par: <%s>' % parameter_s # dbg
648 643
649 644
650 645 # detail_level: 0 -> obj? , 1 -> obj??
651 646 detail_level = 0
652 647 # We need to detect if we got called as 'pinfo pinfo foo', which can
653 648 # happen if the user types 'pinfo foo?' at the cmd line.
654 649 pinfo,qmark1,oname,qmark2 = \
655 650 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
656 651 if pinfo or qmark1 or qmark2:
657 652 detail_level = 1
658 653 if "*" in oname:
659 654 self.magic_psearch(oname)
660 655 else:
661 656 self._inspect('pinfo', oname, detail_level=detail_level,
662 657 namespaces=namespaces)
663 658
664 659 def magic_pdef(self, parameter_s='', namespaces=None):
665 660 """Print the definition header for any callable object.
666 661
667 662 If the object is a class, print the constructor information."""
668 663 self._inspect('pdef',parameter_s, namespaces)
669 664
670 665 def magic_pdoc(self, parameter_s='', namespaces=None):
671 666 """Print the docstring for an object.
672 667
673 668 If the given object is a class, it will print both the class and the
674 669 constructor docstrings."""
675 670 self._inspect('pdoc',parameter_s, namespaces)
676 671
677 672 def magic_psource(self, parameter_s='', namespaces=None):
678 673 """Print (or run through pager) the source code for an object."""
679 674 self._inspect('psource',parameter_s, namespaces)
680 675
681 676 def magic_pfile(self, parameter_s=''):
682 677 """Print (or run through pager) the file where an object is defined.
683 678
684 679 The file opens at the line where the object definition begins. IPython
685 680 will honor the environment variable PAGER if set, and otherwise will
686 681 do its best to print the file in a convenient form.
687 682
688 683 If the given argument is not an object currently defined, IPython will
689 684 try to interpret it as a filename (automatically adding a .py extension
690 685 if needed). You can thus use %pfile as a syntax highlighting code
691 686 viewer."""
692 687
693 688 # first interpret argument as an object name
694 689 out = self._inspect('pfile',parameter_s)
695 690 # if not, try the input as a filename
696 691 if out == 'not found':
697 692 try:
698 693 filename = get_py_filename(parameter_s)
699 694 except IOError,msg:
700 695 print msg
701 696 return
702 697 page(self.shell.inspector.format(file(filename).read()))
703 698
704 699 def _inspect(self,meth,oname,namespaces=None,**kw):
705 700 """Generic interface to the inspector system.
706 701
707 702 This function is meant to be called by pdef, pdoc & friends."""
708 703
709 704 #oname = oname.strip()
710 705 #print '1- oname: <%r>' % oname # dbg
711 706 try:
712 707 oname = oname.strip().encode('ascii')
713 708 #print '2- oname: <%r>' % oname # dbg
714 709 except UnicodeEncodeError:
715 710 print 'Python identifiers can only contain ascii characters.'
716 711 return 'not found'
717 712
718 713 info = Struct(self._ofind(oname, namespaces))
719 714
720 715 if info.found:
721 716 try:
722 717 IPython.generics.inspect_object(info.obj)
723 718 return
724 719 except IPython.ipapi.TryNext:
725 720 pass
726 721 # Get the docstring of the class property if it exists.
727 722 path = oname.split('.')
728 723 root = '.'.join(path[:-1])
729 724 if info.parent is not None:
730 725 try:
731 726 target = getattr(info.parent, '__class__')
732 727 # The object belongs to a class instance.
733 728 try:
734 729 target = getattr(target, path[-1])
735 730 # The class defines the object.
736 731 if isinstance(target, property):
737 732 oname = root + '.__class__.' + path[-1]
738 733 info = Struct(self._ofind(oname))
739 734 except AttributeError: pass
740 735 except AttributeError: pass
741 736
742 737 pmethod = getattr(self.shell.inspector,meth)
743 738 formatter = info.ismagic and self.format_screen or None
744 739 if meth == 'pdoc':
745 740 pmethod(info.obj,oname,formatter)
746 741 elif meth == 'pinfo':
747 742 pmethod(info.obj,oname,formatter,info,**kw)
748 743 else:
749 744 pmethod(info.obj,oname)
750 745 else:
751 746 print 'Object `%s` not found.' % oname
752 747 return 'not found' # so callers can take other action
753 748
754 749 def magic_psearch(self, parameter_s=''):
755 750 """Search for object in namespaces by wildcard.
756 751
757 752 %psearch [options] PATTERN [OBJECT TYPE]
758 753
759 754 Note: ? can be used as a synonym for %psearch, at the beginning or at
760 755 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
761 756 rest of the command line must be unchanged (options come first), so
762 757 for example the following forms are equivalent
763 758
764 759 %psearch -i a* function
765 760 -i a* function?
766 761 ?-i a* function
767 762
768 763 Arguments:
769 764
770 765 PATTERN
771 766
772 767 where PATTERN is a string containing * as a wildcard similar to its
773 768 use in a shell. The pattern is matched in all namespaces on the
774 769 search path. By default objects starting with a single _ are not
775 770 matched, many IPython generated objects have a single
776 771 underscore. The default is case insensitive matching. Matching is
777 772 also done on the attributes of objects and not only on the objects
778 773 in a module.
779 774
780 775 [OBJECT TYPE]
781 776
782 777 Is the name of a python type from the types module. The name is
783 778 given in lowercase without the ending type, ex. StringType is
784 779 written string. By adding a type here only objects matching the
785 780 given type are matched. Using all here makes the pattern match all
786 781 types (this is the default).
787 782
788 783 Options:
789 784
790 785 -a: makes the pattern match even objects whose names start with a
791 786 single underscore. These names are normally ommitted from the
792 787 search.
793 788
794 789 -i/-c: make the pattern case insensitive/sensitive. If neither of
795 790 these options is given, the default is read from your ipythonrc
796 791 file. The option name which sets this value is
797 792 'wildcards_case_sensitive'. If this option is not specified in your
798 793 ipythonrc file, IPython's internal default is to do a case sensitive
799 794 search.
800 795
801 796 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
802 797 specifiy can be searched in any of the following namespaces:
803 798 'builtin', 'user', 'user_global','internal', 'alias', where
804 799 'builtin' and 'user' are the search defaults. Note that you should
805 800 not use quotes when specifying namespaces.
806 801
807 802 'Builtin' contains the python module builtin, 'user' contains all
808 803 user data, 'alias' only contain the shell aliases and no python
809 804 objects, 'internal' contains objects used by IPython. The
810 805 'user_global' namespace is only used by embedded IPython instances,
811 806 and it contains module-level globals. You can add namespaces to the
812 807 search with -s or exclude them with -e (these options can be given
813 808 more than once).
814 809
815 810 Examples:
816 811
817 812 %psearch a* -> objects beginning with an a
818 813 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
819 814 %psearch a* function -> all functions beginning with an a
820 815 %psearch re.e* -> objects beginning with an e in module re
821 816 %psearch r*.e* -> objects that start with e in modules starting in r
822 817 %psearch r*.* string -> all strings in modules beginning with r
823 818
824 819 Case sensitve search:
825 820
826 821 %psearch -c a* list all object beginning with lower case a
827 822
828 823 Show objects beginning with a single _:
829 824
830 825 %psearch -a _* list objects beginning with a single underscore"""
831 826 try:
832 827 parameter_s = parameter_s.encode('ascii')
833 828 except UnicodeEncodeError:
834 829 print 'Python identifiers can only contain ascii characters.'
835 830 return
836 831
837 832 # default namespaces to be searched
838 833 def_search = ['user','builtin']
839 834
840 835 # Process options/args
841 836 opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
842 837 opt = opts.get
843 838 shell = self.shell
844 839 psearch = shell.inspector.psearch
845 840
846 841 # select case options
847 842 if opts.has_key('i'):
848 843 ignore_case = True
849 844 elif opts.has_key('c'):
850 845 ignore_case = False
851 846 else:
852 847 ignore_case = not shell.rc.wildcards_case_sensitive
853 848
854 849 # Build list of namespaces to search from user options
855 850 def_search.extend(opt('s',[]))
856 851 ns_exclude = ns_exclude=opt('e',[])
857 852 ns_search = [nm for nm in def_search if nm not in ns_exclude]
858 853
859 854 # Call the actual search
860 855 try:
861 856 psearch(args,shell.ns_table,ns_search,
862 857 show_all=opt('a'),ignore_case=ignore_case)
863 858 except:
864 859 shell.showtraceback()
865 860
866 861 def magic_who_ls(self, parameter_s=''):
867 862 """Return a sorted list of all interactive variables.
868 863
869 864 If arguments are given, only variables of types matching these
870 865 arguments are returned."""
871 866
872 867 user_ns = self.shell.user_ns
873 868 internal_ns = self.shell.internal_ns
874 869 user_config_ns = self.shell.user_config_ns
875 870 out = []
876 871 typelist = parameter_s.split()
877 872
878 873 for i in user_ns:
879 874 if not (i.startswith('_') or i.startswith('_i')) \
880 875 and not (i in internal_ns or i in user_config_ns):
881 876 if typelist:
882 877 if type(user_ns[i]).__name__ in typelist:
883 878 out.append(i)
884 879 else:
885 880 out.append(i)
886 881 out.sort()
887 882 return out
888 883
889 884 def magic_who(self, parameter_s=''):
890 885 """Print all interactive variables, with some minimal formatting.
891 886
892 887 If any arguments are given, only variables whose type matches one of
893 888 these are printed. For example:
894 889
895 890 %who function str
896 891
897 892 will only list functions and strings, excluding all other types of
898 893 variables. To find the proper type names, simply use type(var) at a
899 894 command line to see how python prints type names. For example:
900 895
901 896 In [1]: type('hello')\\
902 897 Out[1]: <type 'str'>
903 898
904 899 indicates that the type name for strings is 'str'.
905 900
906 901 %who always excludes executed names loaded through your configuration
907 902 file and things which are internal to IPython.
908 903
909 904 This is deliberate, as typically you may load many modules and the
910 905 purpose of %who is to show you only what you've manually defined."""
911 906
912 907 varlist = self.magic_who_ls(parameter_s)
913 908 if not varlist:
914 909 if parameter_s:
915 910 print 'No variables match your requested type.'
916 911 else:
917 912 print 'Interactive namespace is empty.'
918 913 return
919 914
920 915 # if we have variables, move on...
921 916 count = 0
922 917 for i in varlist:
923 918 print i+'\t',
924 919 count += 1
925 920 if count > 8:
926 921 count = 0
927 922 print
928 923 print
929 924
930 925 def magic_whos(self, parameter_s=''):
931 926 """Like %who, but gives some extra information about each variable.
932 927
933 928 The same type filtering of %who can be applied here.
934 929
935 930 For all variables, the type is printed. Additionally it prints:
936 931
937 932 - For {},[],(): their length.
938 933
939 934 - For numpy and Numeric arrays, a summary with shape, number of
940 935 elements, typecode and size in memory.
941 936
942 937 - Everything else: a string representation, snipping their middle if
943 938 too long."""
944 939
945 940 varnames = self.magic_who_ls(parameter_s)
946 941 if not varnames:
947 942 if parameter_s:
948 943 print 'No variables match your requested type.'
949 944 else:
950 945 print 'Interactive namespace is empty.'
951 946 return
952 947
953 948 # if we have variables, move on...
954 949
955 950 # for these types, show len() instead of data:
956 951 seq_types = [types.DictType,types.ListType,types.TupleType]
957 952
958 953 # for numpy/Numeric arrays, display summary info
959 954 try:
960 955 import numpy
961 956 except ImportError:
962 957 ndarray_type = None
963 958 else:
964 959 ndarray_type = numpy.ndarray.__name__
965 960 try:
966 961 import Numeric
967 962 except ImportError:
968 963 array_type = None
969 964 else:
970 965 array_type = Numeric.ArrayType.__name__
971 966
972 967 # Find all variable names and types so we can figure out column sizes
973 968 def get_vars(i):
974 969 return self.shell.user_ns[i]
975 970
976 971 # some types are well known and can be shorter
977 972 abbrevs = {'IPython.macro.Macro' : 'Macro'}
978 973 def type_name(v):
979 974 tn = type(v).__name__
980 975 return abbrevs.get(tn,tn)
981 976
982 977 varlist = map(get_vars,varnames)
983 978
984 979 typelist = []
985 980 for vv in varlist:
986 981 tt = type_name(vv)
987 982
988 983 if tt=='instance':
989 984 typelist.append( abbrevs.get(str(vv.__class__),
990 985 str(vv.__class__)))
991 986 else:
992 987 typelist.append(tt)
993 988
994 989 # column labels and # of spaces as separator
995 990 varlabel = 'Variable'
996 991 typelabel = 'Type'
997 992 datalabel = 'Data/Info'
998 993 colsep = 3
999 994 # variable format strings
1000 995 vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)"
1001 996 vfmt_short = '$vstr[:25]<...>$vstr[-25:]'
1002 997 aformat = "%s: %s elems, type `%s`, %s bytes"
1003 998 # find the size of the columns to format the output nicely
1004 999 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
1005 1000 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
1006 1001 # table header
1007 1002 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
1008 1003 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
1009 1004 # and the table itself
1010 1005 kb = 1024
1011 1006 Mb = 1048576 # kb**2
1012 1007 for vname,var,vtype in zip(varnames,varlist,typelist):
1013 1008 print itpl(vformat),
1014 1009 if vtype in seq_types:
1015 1010 print len(var)
1016 1011 elif vtype in [array_type,ndarray_type]:
1017 1012 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
1018 1013 if vtype==ndarray_type:
1019 1014 # numpy
1020 1015 vsize = var.size
1021 1016 vbytes = vsize*var.itemsize
1022 1017 vdtype = var.dtype
1023 1018 else:
1024 1019 # Numeric
1025 1020 vsize = Numeric.size(var)
1026 1021 vbytes = vsize*var.itemsize()
1027 1022 vdtype = var.typecode()
1028 1023
1029 1024 if vbytes < 100000:
1030 1025 print aformat % (vshape,vsize,vdtype,vbytes)
1031 1026 else:
1032 1027 print aformat % (vshape,vsize,vdtype,vbytes),
1033 1028 if vbytes < Mb:
1034 1029 print '(%s kb)' % (vbytes/kb,)
1035 1030 else:
1036 1031 print '(%s Mb)' % (vbytes/Mb,)
1037 1032 else:
1038 1033 try:
1039 1034 vstr = str(var)
1040 1035 except UnicodeEncodeError:
1041 1036 vstr = unicode(var).encode(sys.getdefaultencoding(),
1042 1037 'backslashreplace')
1043 1038 vstr = vstr.replace('\n','\\n')
1044 1039 if len(vstr) < 50:
1045 1040 print vstr
1046 1041 else:
1047 1042 printpl(vfmt_short)
1048 1043
1049 1044 def magic_reset(self, parameter_s=''):
1050 1045 """Resets the namespace by removing all names defined by the user.
1051 1046
1052 Input/Output history are left around in case you need them."""
1047 Input/Output history are left around in case you need them.
1048
1049 Parameters
1050 ----------
1051 -y : force reset without asking for confirmation.
1052
1053 Examples
1054 --------
1055 In [6]: a = 1
1056
1057 In [7]: a
1058 Out[7]: 1
1059
1060 In [8]: 'a' in _ip.user_ns
1061 Out[8]: True
1062
1063 In [9]: %reset -f
1053 1064
1054 ans = self.shell.ask_yes_no(
1055 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ")
1065 In [10]: 'a' in _ip.user_ns
1066 Out[10]: False
1067 """
1068
1069 if parameter_s == '-f':
1070 ans = True
1071 else:
1072 ans = self.shell.ask_yes_no(
1073 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ")
1056 1074 if not ans:
1057 1075 print 'Nothing done.'
1058 1076 return
1059 1077 user_ns = self.shell.user_ns
1060 1078 for i in self.magic_who_ls():
1061 1079 del(user_ns[i])
1062 1080
1063 1081 # Also flush the private list of module references kept for script
1064 1082 # execution protection
1065 self.shell._user_main_modules[:] = []
1083 self.shell.clear_main_mod_cache()
1066 1084
1067 1085 def magic_logstart(self,parameter_s=''):
1068 1086 """Start logging anywhere in a session.
1069 1087
1070 1088 %logstart [-o|-r|-t] [log_name [log_mode]]
1071 1089
1072 1090 If no name is given, it defaults to a file named 'ipython_log.py' in your
1073 1091 current directory, in 'rotate' mode (see below).
1074 1092
1075 1093 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
1076 1094 history up to that point and then continues logging.
1077 1095
1078 1096 %logstart takes a second optional parameter: logging mode. This can be one
1079 1097 of (note that the modes are given unquoted):\\
1080 1098 append: well, that says it.\\
1081 1099 backup: rename (if exists) to name~ and start name.\\
1082 1100 global: single logfile in your home dir, appended to.\\
1083 1101 over : overwrite existing log.\\
1084 1102 rotate: create rotating logs name.1~, name.2~, etc.
1085 1103
1086 1104 Options:
1087 1105
1088 1106 -o: log also IPython's output. In this mode, all commands which
1089 1107 generate an Out[NN] prompt are recorded to the logfile, right after
1090 1108 their corresponding input line. The output lines are always
1091 1109 prepended with a '#[Out]# ' marker, so that the log remains valid
1092 1110 Python code.
1093 1111
1094 1112 Since this marker is always the same, filtering only the output from
1095 1113 a log is very easy, using for example a simple awk call:
1096 1114
1097 1115 awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py
1098 1116
1099 1117 -r: log 'raw' input. Normally, IPython's logs contain the processed
1100 1118 input, so that user lines are logged in their final form, converted
1101 1119 into valid Python. For example, %Exit is logged as
1102 1120 '_ip.magic("Exit"). If the -r flag is given, all input is logged
1103 1121 exactly as typed, with no transformations applied.
1104 1122
1105 1123 -t: put timestamps before each input line logged (these are put in
1106 1124 comments)."""
1107 1125
1108 1126 opts,par = self.parse_options(parameter_s,'ort')
1109 1127 log_output = 'o' in opts
1110 1128 log_raw_input = 'r' in opts
1111 1129 timestamp = 't' in opts
1112 1130
1113 1131 rc = self.shell.rc
1114 1132 logger = self.shell.logger
1115 1133
1116 1134 # if no args are given, the defaults set in the logger constructor by
1117 1135 # ipytohn remain valid
1118 1136 if par:
1119 1137 try:
1120 1138 logfname,logmode = par.split()
1121 1139 except:
1122 1140 logfname = par
1123 1141 logmode = 'backup'
1124 1142 else:
1125 1143 logfname = logger.logfname
1126 1144 logmode = logger.logmode
1127 1145 # put logfname into rc struct as if it had been called on the command
1128 1146 # line, so it ends up saved in the log header Save it in case we need
1129 1147 # to restore it...
1130 1148 old_logfile = rc.opts.get('logfile','')
1131 1149 if logfname:
1132 1150 logfname = os.path.expanduser(logfname)
1133 1151 rc.opts.logfile = logfname
1134 1152 loghead = self.shell.loghead_tpl % (rc.opts,rc.args)
1135 1153 try:
1136 1154 started = logger.logstart(logfname,loghead,logmode,
1137 1155 log_output,timestamp,log_raw_input)
1138 1156 except:
1139 1157 rc.opts.logfile = old_logfile
1140 1158 warn("Couldn't start log: %s" % sys.exc_info()[1])
1141 1159 else:
1142 1160 # log input history up to this point, optionally interleaving
1143 1161 # output if requested
1144 1162
1145 1163 if timestamp:
1146 1164 # disable timestamping for the previous history, since we've
1147 1165 # lost those already (no time machine here).
1148 1166 logger.timestamp = False
1149 1167
1150 1168 if log_raw_input:
1151 1169 input_hist = self.shell.input_hist_raw
1152 1170 else:
1153 1171 input_hist = self.shell.input_hist
1154 1172
1155 1173 if log_output:
1156 1174 log_write = logger.log_write
1157 1175 output_hist = self.shell.output_hist
1158 1176 for n in range(1,len(input_hist)-1):
1159 1177 log_write(input_hist[n].rstrip())
1160 1178 if n in output_hist:
1161 1179 log_write(repr(output_hist[n]),'output')
1162 1180 else:
1163 1181 logger.log_write(input_hist[1:])
1164 1182 if timestamp:
1165 1183 # re-enable timestamping
1166 1184 logger.timestamp = True
1167 1185
1168 1186 print ('Activating auto-logging. '
1169 1187 'Current session state plus future input saved.')
1170 1188 logger.logstate()
1171 1189
1172 1190 def magic_logstop(self,parameter_s=''):
1173 1191 """Fully stop logging and close log file.
1174 1192
1175 1193 In order to start logging again, a new %logstart call needs to be made,
1176 1194 possibly (though not necessarily) with a new filename, mode and other
1177 1195 options."""
1178 1196 self.logger.logstop()
1179 1197
1180 1198 def magic_logoff(self,parameter_s=''):
1181 1199 """Temporarily stop logging.
1182 1200
1183 1201 You must have previously started logging."""
1184 1202 self.shell.logger.switch_log(0)
1185 1203
1186 1204 def magic_logon(self,parameter_s=''):
1187 1205 """Restart logging.
1188 1206
1189 1207 This function is for restarting logging which you've temporarily
1190 1208 stopped with %logoff. For starting logging for the first time, you
1191 1209 must use the %logstart function, which allows you to specify an
1192 1210 optional log filename."""
1193 1211
1194 1212 self.shell.logger.switch_log(1)
1195 1213
1196 1214 def magic_logstate(self,parameter_s=''):
1197 1215 """Print the status of the logging system."""
1198 1216
1199 1217 self.shell.logger.logstate()
1200 1218
1201 1219 def magic_pdb(self, parameter_s=''):
1202 1220 """Control the automatic calling of the pdb interactive debugger.
1203 1221
1204 1222 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1205 1223 argument it works as a toggle.
1206 1224
1207 1225 When an exception is triggered, IPython can optionally call the
1208 1226 interactive pdb debugger after the traceback printout. %pdb toggles
1209 1227 this feature on and off.
1210 1228
1211 1229 The initial state of this feature is set in your ipythonrc
1212 1230 configuration file (the variable is called 'pdb').
1213 1231
1214 1232 If you want to just activate the debugger AFTER an exception has fired,
1215 1233 without having to type '%pdb on' and rerunning your code, you can use
1216 1234 the %debug magic."""
1217 1235
1218 1236 par = parameter_s.strip().lower()
1219 1237
1220 1238 if par:
1221 1239 try:
1222 1240 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
1223 1241 except KeyError:
1224 1242 print ('Incorrect argument. Use on/1, off/0, '
1225 1243 'or nothing for a toggle.')
1226 1244 return
1227 1245 else:
1228 1246 # toggle
1229 1247 new_pdb = not self.shell.call_pdb
1230 1248
1231 1249 # set on the shell
1232 1250 self.shell.call_pdb = new_pdb
1233 1251 print 'Automatic pdb calling has been turned',on_off(new_pdb)
1234 1252
1235 1253 def magic_debug(self, parameter_s=''):
1236 1254 """Activate the interactive debugger in post-mortem mode.
1237 1255
1238 1256 If an exception has just occurred, this lets you inspect its stack
1239 1257 frames interactively. Note that this will always work only on the last
1240 1258 traceback that occurred, so you must call this quickly after an
1241 1259 exception that you wish to inspect has fired, because if another one
1242 1260 occurs, it clobbers the previous one.
1243 1261
1244 1262 If you want IPython to automatically do this on every exception, see
1245 1263 the %pdb magic for more details.
1246 1264 """
1247 1265
1248 1266 self.shell.debugger(force=True)
1249 1267
1250 1268 @testdec.skip_doctest
1251 1269 def magic_prun(self, parameter_s ='',user_mode=1,
1252 1270 opts=None,arg_lst=None,prog_ns=None):
1253 1271
1254 1272 """Run a statement through the python code profiler.
1255 1273
1256 1274 Usage:
1257 1275 %prun [options] statement
1258 1276
1259 1277 The given statement (which doesn't require quote marks) is run via the
1260 1278 python profiler in a manner similar to the profile.run() function.
1261 1279 Namespaces are internally managed to work correctly; profile.run
1262 1280 cannot be used in IPython because it makes certain assumptions about
1263 1281 namespaces which do not hold under IPython.
1264 1282
1265 1283 Options:
1266 1284
1267 1285 -l <limit>: you can place restrictions on what or how much of the
1268 1286 profile gets printed. The limit value can be:
1269 1287
1270 1288 * A string: only information for function names containing this string
1271 1289 is printed.
1272 1290
1273 1291 * An integer: only these many lines are printed.
1274 1292
1275 1293 * A float (between 0 and 1): this fraction of the report is printed
1276 1294 (for example, use a limit of 0.4 to see the topmost 40% only).
1277 1295
1278 1296 You can combine several limits with repeated use of the option. For
1279 1297 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1280 1298 information about class constructors.
1281 1299
1282 1300 -r: return the pstats.Stats object generated by the profiling. This
1283 1301 object has all the information about the profile in it, and you can
1284 1302 later use it for further analysis or in other functions.
1285 1303
1286 1304 -s <key>: sort profile by given key. You can provide more than one key
1287 1305 by using the option several times: '-s key1 -s key2 -s key3...'. The
1288 1306 default sorting key is 'time'.
1289 1307
1290 1308 The following is copied verbatim from the profile documentation
1291 1309 referenced below:
1292 1310
1293 1311 When more than one key is provided, additional keys are used as
1294 1312 secondary criteria when the there is equality in all keys selected
1295 1313 before them.
1296 1314
1297 1315 Abbreviations can be used for any key names, as long as the
1298 1316 abbreviation is unambiguous. The following are the keys currently
1299 1317 defined:
1300 1318
1301 1319 Valid Arg Meaning
1302 1320 "calls" call count
1303 1321 "cumulative" cumulative time
1304 1322 "file" file name
1305 1323 "module" file name
1306 1324 "pcalls" primitive call count
1307 1325 "line" line number
1308 1326 "name" function name
1309 1327 "nfl" name/file/line
1310 1328 "stdname" standard name
1311 1329 "time" internal time
1312 1330
1313 1331 Note that all sorts on statistics are in descending order (placing
1314 1332 most time consuming items first), where as name, file, and line number
1315 1333 searches are in ascending order (i.e., alphabetical). The subtle
1316 1334 distinction between "nfl" and "stdname" is that the standard name is a
1317 1335 sort of the name as printed, which means that the embedded line
1318 1336 numbers get compared in an odd way. For example, lines 3, 20, and 40
1319 1337 would (if the file names were the same) appear in the string order
1320 1338 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1321 1339 line numbers. In fact, sort_stats("nfl") is the same as
1322 1340 sort_stats("name", "file", "line").
1323 1341
1324 1342 -T <filename>: save profile results as shown on screen to a text
1325 1343 file. The profile is still shown on screen.
1326 1344
1327 1345 -D <filename>: save (via dump_stats) profile statistics to given
1328 1346 filename. This data is in a format understod by the pstats module, and
1329 1347 is generated by a call to the dump_stats() method of profile
1330 1348 objects. The profile is still shown on screen.
1331 1349
1332 1350 If you want to run complete programs under the profiler's control, use
1333 1351 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1334 1352 contains profiler specific options as described here.
1335 1353
1336 1354 You can read the complete documentation for the profile module with::
1337 1355
1338 1356 In [1]: import profile; profile.help()
1339 1357 """
1340 1358
1341 1359 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1342 1360 # protect user quote marks
1343 1361 parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'")
1344 1362
1345 1363 if user_mode: # regular user call
1346 1364 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:',
1347 1365 list_all=1)
1348 1366 namespace = self.shell.user_ns
1349 1367 else: # called to run a program by %run -p
1350 1368 try:
1351 1369 filename = get_py_filename(arg_lst[0])
1352 1370 except IOError,msg:
1353 1371 error(msg)
1354 1372 return
1355 1373
1356 1374 arg_str = 'execfile(filename,prog_ns)'
1357 1375 namespace = locals()
1358 1376
1359 1377 opts.merge(opts_def)
1360 1378
1361 1379 prof = profile.Profile()
1362 1380 try:
1363 1381 prof = prof.runctx(arg_str,namespace,namespace)
1364 1382 sys_exit = ''
1365 1383 except SystemExit:
1366 1384 sys_exit = """*** SystemExit exception caught in code being profiled."""
1367 1385
1368 1386 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1369 1387
1370 1388 lims = opts.l
1371 1389 if lims:
1372 1390 lims = [] # rebuild lims with ints/floats/strings
1373 1391 for lim in opts.l:
1374 1392 try:
1375 1393 lims.append(int(lim))
1376 1394 except ValueError:
1377 1395 try:
1378 1396 lims.append(float(lim))
1379 1397 except ValueError:
1380 1398 lims.append(lim)
1381 1399
1382 1400 # Trap output.
1383 1401 stdout_trap = StringIO()
1384 1402
1385 1403 if hasattr(stats,'stream'):
1386 1404 # In newer versions of python, the stats object has a 'stream'
1387 1405 # attribute to write into.
1388 1406 stats.stream = stdout_trap
1389 1407 stats.print_stats(*lims)
1390 1408 else:
1391 1409 # For older versions, we manually redirect stdout during printing
1392 1410 sys_stdout = sys.stdout
1393 1411 try:
1394 1412 sys.stdout = stdout_trap
1395 1413 stats.print_stats(*lims)
1396 1414 finally:
1397 1415 sys.stdout = sys_stdout
1398 1416
1399 1417 output = stdout_trap.getvalue()
1400 1418 output = output.rstrip()
1401 1419
1402 1420 page(output,screen_lines=self.shell.rc.screen_length)
1403 1421 print sys_exit,
1404 1422
1405 1423 dump_file = opts.D[0]
1406 1424 text_file = opts.T[0]
1407 1425 if dump_file:
1408 1426 prof.dump_stats(dump_file)
1409 1427 print '\n*** Profile stats marshalled to file',\
1410 1428 `dump_file`+'.',sys_exit
1411 1429 if text_file:
1412 1430 pfile = file(text_file,'w')
1413 1431 pfile.write(output)
1414 1432 pfile.close()
1415 1433 print '\n*** Profile printout saved to text file',\
1416 1434 `text_file`+'.',sys_exit
1417 1435
1418 1436 if opts.has_key('r'):
1419 1437 return stats
1420 1438 else:
1421 1439 return None
1422 1440
1423 1441 @testdec.skip_doctest
1424 1442 def magic_run(self, parameter_s ='',runner=None,
1425 1443 file_finder=get_py_filename):
1426 1444 """Run the named file inside IPython as a program.
1427 1445
1428 1446 Usage:\\
1429 1447 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1430 1448
1431 1449 Parameters after the filename are passed as command-line arguments to
1432 1450 the program (put in sys.argv). Then, control returns to IPython's
1433 1451 prompt.
1434 1452
1435 1453 This is similar to running at a system prompt:\\
1436 1454 $ python file args\\
1437 1455 but with the advantage of giving you IPython's tracebacks, and of
1438 1456 loading all variables into your interactive namespace for further use
1439 1457 (unless -p is used, see below).
1440 1458
1441 1459 The file is executed in a namespace initially consisting only of
1442 1460 __name__=='__main__' and sys.argv constructed as indicated. It thus
1443 1461 sees its environment as if it were being run as a stand-alone program
1444 1462 (except for sharing global objects such as previously imported
1445 1463 modules). But after execution, the IPython interactive namespace gets
1446 1464 updated with all variables defined in the program (except for __name__
1447 1465 and sys.argv). This allows for very convenient loading of code for
1448 1466 interactive work, while giving each program a 'clean sheet' to run in.
1449 1467
1450 1468 Options:
1451 1469
1452 1470 -n: __name__ is NOT set to '__main__', but to the running file's name
1453 1471 without extension (as python does under import). This allows running
1454 1472 scripts and reloading the definitions in them without calling code
1455 1473 protected by an ' if __name__ == "__main__" ' clause.
1456 1474
1457 1475 -i: run the file in IPython's namespace instead of an empty one. This
1458 1476 is useful if you are experimenting with code written in a text editor
1459 1477 which depends on variables defined interactively.
1460 1478
1461 1479 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1462 1480 being run. This is particularly useful if IPython is being used to
1463 1481 run unittests, which always exit with a sys.exit() call. In such
1464 1482 cases you are interested in the output of the test results, not in
1465 1483 seeing a traceback of the unittest module.
1466 1484
1467 1485 -t: print timing information at the end of the run. IPython will give
1468 1486 you an estimated CPU time consumption for your script, which under
1469 1487 Unix uses the resource module to avoid the wraparound problems of
1470 1488 time.clock(). Under Unix, an estimate of time spent on system tasks
1471 1489 is also given (for Windows platforms this is reported as 0.0).
1472 1490
1473 1491 If -t is given, an additional -N<N> option can be given, where <N>
1474 1492 must be an integer indicating how many times you want the script to
1475 1493 run. The final timing report will include total and per run results.
1476 1494
1477 1495 For example (testing the script uniq_stable.py):
1478 1496
1479 1497 In [1]: run -t uniq_stable
1480 1498
1481 1499 IPython CPU timings (estimated):\\
1482 1500 User : 0.19597 s.\\
1483 1501 System: 0.0 s.\\
1484 1502
1485 1503 In [2]: run -t -N5 uniq_stable
1486 1504
1487 1505 IPython CPU timings (estimated):\\
1488 1506 Total runs performed: 5\\
1489 1507 Times : Total Per run\\
1490 1508 User : 0.910862 s, 0.1821724 s.\\
1491 1509 System: 0.0 s, 0.0 s.
1492 1510
1493 1511 -d: run your program under the control of pdb, the Python debugger.
1494 1512 This allows you to execute your program step by step, watch variables,
1495 1513 etc. Internally, what IPython does is similar to calling:
1496 1514
1497 1515 pdb.run('execfile("YOURFILENAME")')
1498 1516
1499 1517 with a breakpoint set on line 1 of your file. You can change the line
1500 1518 number for this automatic breakpoint to be <N> by using the -bN option
1501 1519 (where N must be an integer). For example:
1502 1520
1503 1521 %run -d -b40 myscript
1504 1522
1505 1523 will set the first breakpoint at line 40 in myscript.py. Note that
1506 1524 the first breakpoint must be set on a line which actually does
1507 1525 something (not a comment or docstring) for it to stop execution.
1508 1526
1509 1527 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1510 1528 first enter 'c' (without qoutes) to start execution up to the first
1511 1529 breakpoint.
1512 1530
1513 1531 Entering 'help' gives information about the use of the debugger. You
1514 1532 can easily see pdb's full documentation with "import pdb;pdb.help()"
1515 1533 at a prompt.
1516 1534
1517 1535 -p: run program under the control of the Python profiler module (which
1518 1536 prints a detailed report of execution times, function calls, etc).
1519 1537
1520 1538 You can pass other options after -p which affect the behavior of the
1521 1539 profiler itself. See the docs for %prun for details.
1522 1540
1523 1541 In this mode, the program's variables do NOT propagate back to the
1524 1542 IPython interactive namespace (because they remain in the namespace
1525 1543 where the profiler executes them).
1526 1544
1527 1545 Internally this triggers a call to %prun, see its documentation for
1528 1546 details on the options available specifically for profiling.
1529 1547
1530 1548 There is one special usage for which the text above doesn't apply:
1531 1549 if the filename ends with .ipy, the file is run as ipython script,
1532 1550 just as if the commands were written on IPython prompt.
1533 1551 """
1534 1552
1535 1553 # get arguments and set sys.argv for program to be run.
1536 1554 opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e',
1537 1555 mode='list',list_all=1)
1538 1556
1539 1557 try:
1540 1558 filename = file_finder(arg_lst[0])
1541 1559 except IndexError:
1542 1560 warn('you must provide at least a filename.')
1543 1561 print '\n%run:\n',OInspect.getdoc(self.magic_run)
1544 1562 return
1545 1563 except IOError,msg:
1546 1564 error(msg)
1547 1565 return
1548 1566
1549 1567 if filename.lower().endswith('.ipy'):
1550 1568 self.api.runlines(open(filename).read())
1551 1569 return
1552 1570
1553 1571 # Control the response to exit() calls made by the script being run
1554 1572 exit_ignore = opts.has_key('e')
1555 1573
1556 1574 # Make sure that the running script gets a proper sys.argv as if it
1557 1575 # were run from a system shell.
1558 1576 save_argv = sys.argv # save it for later restoring
1559 1577 sys.argv = [filename]+ arg_lst[1:] # put in the proper filename
1560 1578
1561 1579 if opts.has_key('i'):
1562 1580 # Run in user's interactive namespace
1563 1581 prog_ns = self.shell.user_ns
1564 1582 __name__save = self.shell.user_ns['__name__']
1565 1583 prog_ns['__name__'] = '__main__'
1566 1584 main_mod = FakeModule(prog_ns)
1567 1585 else:
1568 1586 # Run in a fresh, empty namespace
1569 1587 if opts.has_key('n'):
1570 1588 name = os.path.splitext(os.path.basename(filename))[0]
1571 1589 else:
1572 1590 name = '__main__'
1573 1591 main_mod = FakeModule()
1574 1592 prog_ns = main_mod.__dict__
1575 1593 prog_ns['__name__'] = name
1576 1594
1577 1595 # The shell MUST hold a reference to main_mod so after %run exits,
1578 1596 # the python deletion mechanism doesn't zero it out (leaving
1579 # dangling references)
1580
1581 # XXX - the note above was written without further detail, but this
1582 # code actually causes problems. By holding references to the
1583 # namespace where every script is executed, we effectively disable
1584 # just about all possible variable cleanup. In particular,
1585 # generator expressions and other variables that point to open
1586 # files are kept alive, and as a user session lives on, it may run
1587 # out of available file descriptors. Such a bug has already been
1588 # reported by JD Hunter. I'm disabling this for now, but we need
1589 # to clarify exactly (and add tests) what from main_mod needs to be
1590 # kept alive and what is save to remove... In fact, see note
1591 # below, where we append main_mod to sys.modules and then delete it
1592 # again. The final cleanup is rendered moot by this reference kept
1593 # in _user_main_modules(), so we really need to look into this.
1594
1595 self.shell._user_main_modules.append(main_mod)
1596
1597 # /XXX
1597 # dangling references). However, we should drop old versions of
1598 # main_mod. There is now a proper API to manage this caching in
1599 # the main shell object, we use that.
1600 self.shell.cache_main_mod(main_mod)
1598 1601
1599 1602 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
1600 1603 # set the __file__ global in the script's namespace
1601 1604 prog_ns['__file__'] = filename
1602 1605
1603 1606 # pickle fix. See iplib for an explanation. But we need to make sure
1604 1607 # that, if we overwrite __main__, we replace it at the end
1605 1608 main_mod_name = prog_ns['__name__']
1606 1609
1607 1610 if main_mod_name == '__main__':
1608 1611 restore_main = sys.modules['__main__']
1609 1612 else:
1610 1613 restore_main = False
1611 1614
1612 1615 # This needs to be undone at the end to prevent holding references to
1613 1616 # every single object ever created.
1614 1617 sys.modules[main_mod_name] = main_mod
1615 1618
1616 1619 stats = None
1617 1620 try:
1618 1621 self.shell.savehist()
1619 1622
1620 1623 if opts.has_key('p'):
1621 1624 stats = self.magic_prun('',0,opts,arg_lst,prog_ns)
1622 1625 else:
1623 1626 if opts.has_key('d'):
1624 1627 deb = Debugger.Pdb(self.shell.rc.colors)
1625 1628 # reset Breakpoint state, which is moronically kept
1626 1629 # in a class
1627 1630 bdb.Breakpoint.next = 1
1628 1631 bdb.Breakpoint.bplist = {}
1629 1632 bdb.Breakpoint.bpbynumber = [None]
1630 1633 # Set an initial breakpoint to stop execution
1631 1634 maxtries = 10
1632 1635 bp = int(opts.get('b',[1])[0])
1633 1636 checkline = deb.checkline(filename,bp)
1634 1637 if not checkline:
1635 1638 for bp in range(bp+1,bp+maxtries+1):
1636 1639 if deb.checkline(filename,bp):
1637 1640 break
1638 1641 else:
1639 1642 msg = ("\nI failed to find a valid line to set "
1640 1643 "a breakpoint\n"
1641 1644 "after trying up to line: %s.\n"
1642 1645 "Please set a valid breakpoint manually "
1643 1646 "with the -b option." % bp)
1644 1647 error(msg)
1645 1648 return
1646 1649 # if we find a good linenumber, set the breakpoint
1647 1650 deb.do_break('%s:%s' % (filename,bp))
1648 1651 # Start file run
1649 1652 print "NOTE: Enter 'c' at the",
1650 1653 print "%s prompt to start your script." % deb.prompt
1651 1654 try:
1652 1655 deb.run('execfile("%s")' % filename,prog_ns)
1653 1656
1654 1657 except:
1655 1658 etype, value, tb = sys.exc_info()
1656 1659 # Skip three frames in the traceback: the %run one,
1657 1660 # one inside bdb.py, and the command-line typed by the
1658 1661 # user (run by exec in pdb itself).
1659 1662 self.shell.InteractiveTB(etype,value,tb,tb_offset=3)
1660 1663 else:
1661 1664 if runner is None:
1662 1665 runner = self.shell.safe_execfile
1663 1666 if opts.has_key('t'):
1664 1667 # timed execution
1665 1668 try:
1666 1669 nruns = int(opts['N'][0])
1667 1670 if nruns < 1:
1668 1671 error('Number of runs must be >=1')
1669 1672 return
1670 1673 except (KeyError):
1671 1674 nruns = 1
1672 1675 if nruns == 1:
1673 1676 t0 = clock2()
1674 1677 runner(filename,prog_ns,prog_ns,
1675 1678 exit_ignore=exit_ignore)
1676 1679 t1 = clock2()
1677 1680 t_usr = t1[0]-t0[0]
1678 1681 t_sys = t1[1]-t1[1]
1679 1682 print "\nIPython CPU timings (estimated):"
1680 1683 print " User : %10s s." % t_usr
1681 1684 print " System: %10s s." % t_sys
1682 1685 else:
1683 1686 runs = range(nruns)
1684 1687 t0 = clock2()
1685 1688 for nr in runs:
1686 1689 runner(filename,prog_ns,prog_ns,
1687 1690 exit_ignore=exit_ignore)
1688 1691 t1 = clock2()
1689 1692 t_usr = t1[0]-t0[0]
1690 1693 t_sys = t1[1]-t1[1]
1691 1694 print "\nIPython CPU timings (estimated):"
1692 1695 print "Total runs performed:",nruns
1693 1696 print " Times : %10s %10s" % ('Total','Per run')
1694 1697 print " User : %10s s, %10s s." % (t_usr,t_usr/nruns)
1695 1698 print " System: %10s s, %10s s." % (t_sys,t_sys/nruns)
1696 1699
1697 1700 else:
1698 1701 # regular execution
1699 1702 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1700 1703 if opts.has_key('i'):
1701 1704 self.shell.user_ns['__name__'] = __name__save
1702 1705 else:
1703 1706 # update IPython interactive namespace
1704 1707 del prog_ns['__name__']
1705 1708 self.shell.user_ns.update(prog_ns)
1706 1709 finally:
1707 1710 # Ensure key global structures are restored
1708 1711 sys.argv = save_argv
1709 1712 if restore_main:
1710 1713 sys.modules['__main__'] = restore_main
1711 1714 else:
1712 1715 # Remove from sys.modules the reference to main_mod we'd
1713 1716 # added. Otherwise it will trap references to objects
1714 1717 # contained therein.
1715 1718 del sys.modules[main_mod_name]
1716 1719 self.shell.reloadhist()
1717 1720
1718 1721 return stats
1719 1722
1720 1723 def magic_runlog(self, parameter_s =''):
1721 1724 """Run files as logs.
1722 1725
1723 1726 Usage:\\
1724 1727 %runlog file1 file2 ...
1725 1728
1726 1729 Run the named files (treating them as log files) in sequence inside
1727 1730 the interpreter, and return to the prompt. This is much slower than
1728 1731 %run because each line is executed in a try/except block, but it
1729 1732 allows running files with syntax errors in them.
1730 1733
1731 1734 Normally IPython will guess when a file is one of its own logfiles, so
1732 1735 you can typically use %run even for logs. This shorthand allows you to
1733 1736 force any file to be treated as a log file."""
1734 1737
1735 1738 for f in parameter_s.split():
1736 1739 self.shell.safe_execfile(f,self.shell.user_ns,
1737 1740 self.shell.user_ns,islog=1)
1738 1741
1739 1742 @testdec.skip_doctest
1740 1743 def magic_timeit(self, parameter_s =''):
1741 1744 """Time execution of a Python statement or expression
1742 1745
1743 1746 Usage:\\
1744 1747 %timeit [-n<N> -r<R> [-t|-c]] statement
1745 1748
1746 1749 Time execution of a Python statement or expression using the timeit
1747 1750 module.
1748 1751
1749 1752 Options:
1750 1753 -n<N>: execute the given statement <N> times in a loop. If this value
1751 1754 is not given, a fitting value is chosen.
1752 1755
1753 1756 -r<R>: repeat the loop iteration <R> times and take the best result.
1754 1757 Default: 3
1755 1758
1756 1759 -t: use time.time to measure the time, which is the default on Unix.
1757 1760 This function measures wall time.
1758 1761
1759 1762 -c: use time.clock to measure the time, which is the default on
1760 1763 Windows and measures wall time. On Unix, resource.getrusage is used
1761 1764 instead and returns the CPU user time.
1762 1765
1763 1766 -p<P>: use a precision of <P> digits to display the timing result.
1764 1767 Default: 3
1765 1768
1766 1769
1767 1770 Examples:
1768 1771
1769 1772 In [1]: %timeit pass
1770 1773 10000000 loops, best of 3: 53.3 ns per loop
1771 1774
1772 1775 In [2]: u = None
1773 1776
1774 1777 In [3]: %timeit u is None
1775 1778 10000000 loops, best of 3: 184 ns per loop
1776 1779
1777 1780 In [4]: %timeit -r 4 u == None
1778 1781 1000000 loops, best of 4: 242 ns per loop
1779 1782
1780 1783 In [5]: import time
1781 1784
1782 1785 In [6]: %timeit -n1 time.sleep(2)
1783 1786 1 loops, best of 3: 2 s per loop
1784 1787
1785 1788
1786 1789 The times reported by %timeit will be slightly higher than those
1787 1790 reported by the timeit.py script when variables are accessed. This is
1788 1791 due to the fact that %timeit executes the statement in the namespace
1789 1792 of the shell, compared with timeit.py, which uses a single setup
1790 1793 statement to import function or create variables. Generally, the bias
1791 1794 does not matter as long as results from timeit.py are not mixed with
1792 1795 those from %timeit."""
1793 1796
1794 1797 import timeit
1795 1798 import math
1796 1799
1797 1800 units = [u"s", u"ms", u"\xb5s", u"ns"]
1798 1801 scaling = [1, 1e3, 1e6, 1e9]
1799 1802
1800 1803 opts, stmt = self.parse_options(parameter_s,'n:r:tcp:',
1801 1804 posix=False)
1802 1805 if stmt == "":
1803 1806 return
1804 1807 timefunc = timeit.default_timer
1805 1808 number = int(getattr(opts, "n", 0))
1806 1809 repeat = int(getattr(opts, "r", timeit.default_repeat))
1807 1810 precision = int(getattr(opts, "p", 3))
1808 1811 if hasattr(opts, "t"):
1809 1812 timefunc = time.time
1810 1813 if hasattr(opts, "c"):
1811 1814 timefunc = clock
1812 1815
1813 1816 timer = timeit.Timer(timer=timefunc)
1814 1817 # this code has tight coupling to the inner workings of timeit.Timer,
1815 1818 # but is there a better way to achieve that the code stmt has access
1816 1819 # to the shell namespace?
1817 1820
1818 1821 src = timeit.template % {'stmt': timeit.reindent(stmt, 8),
1819 1822 'setup': "pass"}
1820 1823 # Track compilation time so it can be reported if too long
1821 1824 # Minimum time above which compilation time will be reported
1822 1825 tc_min = 0.1
1823 1826
1824 1827 t0 = clock()
1825 1828 code = compile(src, "<magic-timeit>", "exec")
1826 1829 tc = clock()-t0
1827 1830
1828 1831 ns = {}
1829 1832 exec code in self.shell.user_ns, ns
1830 1833 timer.inner = ns["inner"]
1831 1834
1832 1835 if number == 0:
1833 1836 # determine number so that 0.2 <= total time < 2.0
1834 1837 number = 1
1835 1838 for i in range(1, 10):
1836 1839 number *= 10
1837 1840 if timer.timeit(number) >= 0.2:
1838 1841 break
1839 1842
1840 1843 best = min(timer.repeat(repeat, number)) / number
1841 1844
1842 1845 if best > 0.0:
1843 1846 order = min(-int(math.floor(math.log10(best)) // 3), 3)
1844 1847 else:
1845 1848 order = 3
1846 1849 print u"%d loops, best of %d: %.*g %s per loop" % (number, repeat,
1847 1850 precision,
1848 1851 best * scaling[order],
1849 1852 units[order])
1850 1853 if tc > tc_min:
1851 1854 print "Compiler time: %.2f s" % tc
1852 1855
1853 1856 @testdec.skip_doctest
1854 1857 def magic_time(self,parameter_s = ''):
1855 1858 """Time execution of a Python statement or expression.
1856 1859
1857 1860 The CPU and wall clock times are printed, and the value of the
1858 1861 expression (if any) is returned. Note that under Win32, system time
1859 1862 is always reported as 0, since it can not be measured.
1860 1863
1861 1864 This function provides very basic timing functionality. In Python
1862 1865 2.3, the timeit module offers more control and sophistication, so this
1863 1866 could be rewritten to use it (patches welcome).
1864 1867
1865 1868 Some examples:
1866 1869
1867 1870 In [1]: time 2**128
1868 1871 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1869 1872 Wall time: 0.00
1870 1873 Out[1]: 340282366920938463463374607431768211456L
1871 1874
1872 1875 In [2]: n = 1000000
1873 1876
1874 1877 In [3]: time sum(range(n))
1875 1878 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1876 1879 Wall time: 1.37
1877 1880 Out[3]: 499999500000L
1878 1881
1879 1882 In [4]: time print 'hello world'
1880 1883 hello world
1881 1884 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1882 1885 Wall time: 0.00
1883 1886
1884 1887 Note that the time needed by Python to compile the given expression
1885 1888 will be reported if it is more than 0.1s. In this example, the
1886 1889 actual exponentiation is done by Python at compilation time, so while
1887 1890 the expression can take a noticeable amount of time to compute, that
1888 1891 time is purely due to the compilation:
1889 1892
1890 1893 In [5]: time 3**9999;
1891 1894 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1892 1895 Wall time: 0.00 s
1893 1896
1894 1897 In [6]: time 3**999999;
1895 1898 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1896 1899 Wall time: 0.00 s
1897 1900 Compiler : 0.78 s
1898 1901 """
1899 1902
1900 1903 # fail immediately if the given expression can't be compiled
1901 1904
1902 1905 expr = self.shell.prefilter(parameter_s,False)
1903 1906
1904 1907 # Minimum time above which compilation time will be reported
1905 1908 tc_min = 0.1
1906 1909
1907 1910 try:
1908 1911 mode = 'eval'
1909 1912 t0 = clock()
1910 1913 code = compile(expr,'<timed eval>',mode)
1911 1914 tc = clock()-t0
1912 1915 except SyntaxError:
1913 1916 mode = 'exec'
1914 1917 t0 = clock()
1915 1918 code = compile(expr,'<timed exec>',mode)
1916 1919 tc = clock()-t0
1917 1920 # skew measurement as little as possible
1918 1921 glob = self.shell.user_ns
1919 1922 clk = clock2
1920 1923 wtime = time.time
1921 1924 # time execution
1922 1925 wall_st = wtime()
1923 1926 if mode=='eval':
1924 1927 st = clk()
1925 1928 out = eval(code,glob)
1926 1929 end = clk()
1927 1930 else:
1928 1931 st = clk()
1929 1932 exec code in glob
1930 1933 end = clk()
1931 1934 out = None
1932 1935 wall_end = wtime()
1933 1936 # Compute actual times and report
1934 1937 wall_time = wall_end-wall_st
1935 1938 cpu_user = end[0]-st[0]
1936 1939 cpu_sys = end[1]-st[1]
1937 1940 cpu_tot = cpu_user+cpu_sys
1938 1941 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
1939 1942 (cpu_user,cpu_sys,cpu_tot)
1940 1943 print "Wall time: %.2f s" % wall_time
1941 1944 if tc > tc_min:
1942 1945 print "Compiler : %.2f s" % tc
1943 1946 return out
1944 1947
1945 1948 @testdec.skip_doctest
1946 1949 def magic_macro(self,parameter_s = ''):
1947 1950 """Define a set of input lines as a macro for future re-execution.
1948 1951
1949 1952 Usage:\\
1950 1953 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
1951 1954
1952 1955 Options:
1953 1956
1954 1957 -r: use 'raw' input. By default, the 'processed' history is used,
1955 1958 so that magics are loaded in their transformed version to valid
1956 1959 Python. If this option is given, the raw input as typed as the
1957 1960 command line is used instead.
1958 1961
1959 1962 This will define a global variable called `name` which is a string
1960 1963 made of joining the slices and lines you specify (n1,n2,... numbers
1961 1964 above) from your input history into a single string. This variable
1962 1965 acts like an automatic function which re-executes those lines as if
1963 1966 you had typed them. You just type 'name' at the prompt and the code
1964 1967 executes.
1965 1968
1966 1969 The notation for indicating number ranges is: n1-n2 means 'use line
1967 1970 numbers n1,...n2' (the endpoint is included). That is, '5-7' means
1968 1971 using the lines numbered 5,6 and 7.
1969 1972
1970 1973 Note: as a 'hidden' feature, you can also use traditional python slice
1971 1974 notation, where N:M means numbers N through M-1.
1972 1975
1973 1976 For example, if your history contains (%hist prints it):
1974 1977
1975 1978 44: x=1
1976 1979 45: y=3
1977 1980 46: z=x+y
1978 1981 47: print x
1979 1982 48: a=5
1980 1983 49: print 'x',x,'y',y
1981 1984
1982 1985 you can create a macro with lines 44 through 47 (included) and line 49
1983 1986 called my_macro with:
1984 1987
1985 1988 In [55]: %macro my_macro 44-47 49
1986 1989
1987 1990 Now, typing `my_macro` (without quotes) will re-execute all this code
1988 1991 in one pass.
1989 1992
1990 1993 You don't need to give the line-numbers in order, and any given line
1991 1994 number can appear multiple times. You can assemble macros with any
1992 1995 lines from your input history in any order.
1993 1996
1994 1997 The macro is a simple object which holds its value in an attribute,
1995 1998 but IPython's display system checks for macros and executes them as
1996 1999 code instead of printing them when you type their name.
1997 2000
1998 2001 You can view a macro's contents by explicitly printing it with:
1999 2002
2000 2003 'print macro_name'.
2001 2004
2002 2005 For one-off cases which DON'T contain magic function calls in them you
2003 2006 can obtain similar results by explicitly executing slices from your
2004 2007 input history with:
2005 2008
2006 2009 In [60]: exec In[44:48]+In[49]"""
2007 2010
2008 2011 opts,args = self.parse_options(parameter_s,'r',mode='list')
2009 2012 if not args:
2010 2013 macs = [k for k,v in self.shell.user_ns.items() if isinstance(v, Macro)]
2011 2014 macs.sort()
2012 2015 return macs
2013 2016 if len(args) == 1:
2014 2017 raise UsageError(
2015 2018 "%macro insufficient args; usage '%macro name n1-n2 n3-4...")
2016 2019 name,ranges = args[0], args[1:]
2017 2020
2018 2021 #print 'rng',ranges # dbg
2019 2022 lines = self.extract_input_slices(ranges,opts.has_key('r'))
2020 2023 macro = Macro(lines)
2021 2024 self.shell.user_ns.update({name:macro})
2022 2025 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
2023 2026 print 'Macro contents:'
2024 2027 print macro,
2025 2028
2026 2029 def magic_save(self,parameter_s = ''):
2027 2030 """Save a set of lines to a given filename.
2028 2031
2029 2032 Usage:\\
2030 2033 %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ...
2031 2034
2032 2035 Options:
2033 2036
2034 2037 -r: use 'raw' input. By default, the 'processed' history is used,
2035 2038 so that magics are loaded in their transformed version to valid
2036 2039 Python. If this option is given, the raw input as typed as the
2037 2040 command line is used instead.
2038 2041
2039 2042 This function uses the same syntax as %macro for line extraction, but
2040 2043 instead of creating a macro it saves the resulting string to the
2041 2044 filename you specify.
2042 2045
2043 2046 It adds a '.py' extension to the file if you don't do so yourself, and
2044 2047 it asks for confirmation before overwriting existing files."""
2045 2048
2046 2049 opts,args = self.parse_options(parameter_s,'r',mode='list')
2047 2050 fname,ranges = args[0], args[1:]
2048 2051 if not fname.endswith('.py'):
2049 2052 fname += '.py'
2050 2053 if os.path.isfile(fname):
2051 2054 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
2052 2055 if ans.lower() not in ['y','yes']:
2053 2056 print 'Operation cancelled.'
2054 2057 return
2055 2058 cmds = ''.join(self.extract_input_slices(ranges,opts.has_key('r')))
2056 2059 f = file(fname,'w')
2057 2060 f.write(cmds)
2058 2061 f.close()
2059 2062 print 'The following commands were written to file `%s`:' % fname
2060 2063 print cmds
2061 2064
2062 2065 def _edit_macro(self,mname,macro):
2063 2066 """open an editor with the macro data in a file"""
2064 2067 filename = self.shell.mktempfile(macro.value)
2065 2068 self.shell.hooks.editor(filename)
2066 2069
2067 2070 # and make a new macro object, to replace the old one
2068 2071 mfile = open(filename)
2069 2072 mvalue = mfile.read()
2070 2073 mfile.close()
2071 2074 self.shell.user_ns[mname] = Macro(mvalue)
2072 2075
2073 2076 def magic_ed(self,parameter_s=''):
2074 2077 """Alias to %edit."""
2075 2078 return self.magic_edit(parameter_s)
2076 2079
2077 2080 @testdec.skip_doctest
2078 2081 def magic_edit(self,parameter_s='',last_call=['','']):
2079 2082 """Bring up an editor and execute the resulting code.
2080 2083
2081 2084 Usage:
2082 2085 %edit [options] [args]
2083 2086
2084 2087 %edit runs IPython's editor hook. The default version of this hook is
2085 2088 set to call the __IPYTHON__.rc.editor command. This is read from your
2086 2089 environment variable $EDITOR. If this isn't found, it will default to
2087 2090 vi under Linux/Unix and to notepad under Windows. See the end of this
2088 2091 docstring for how to change the editor hook.
2089 2092
2090 2093 You can also set the value of this editor via the command line option
2091 2094 '-editor' or in your ipythonrc file. This is useful if you wish to use
2092 2095 specifically for IPython an editor different from your typical default
2093 2096 (and for Windows users who typically don't set environment variables).
2094 2097
2095 2098 This command allows you to conveniently edit multi-line code right in
2096 2099 your IPython session.
2097 2100
2098 2101 If called without arguments, %edit opens up an empty editor with a
2099 2102 temporary file and will execute the contents of this file when you
2100 2103 close it (don't forget to save it!).
2101 2104
2102 2105
2103 2106 Options:
2104 2107
2105 2108 -n <number>: open the editor at a specified line number. By default,
2106 2109 the IPython editor hook uses the unix syntax 'editor +N filename', but
2107 2110 you can configure this by providing your own modified hook if your
2108 2111 favorite editor supports line-number specifications with a different
2109 2112 syntax.
2110 2113
2111 2114 -p: this will call the editor with the same data as the previous time
2112 2115 it was used, regardless of how long ago (in your current session) it
2113 2116 was.
2114 2117
2115 2118 -r: use 'raw' input. This option only applies to input taken from the
2116 2119 user's history. By default, the 'processed' history is used, so that
2117 2120 magics are loaded in their transformed version to valid Python. If
2118 2121 this option is given, the raw input as typed as the command line is
2119 2122 used instead. When you exit the editor, it will be executed by
2120 2123 IPython's own processor.
2121 2124
2122 2125 -x: do not execute the edited code immediately upon exit. This is
2123 2126 mainly useful if you are editing programs which need to be called with
2124 2127 command line arguments, which you can then do using %run.
2125 2128
2126 2129
2127 2130 Arguments:
2128 2131
2129 2132 If arguments are given, the following possibilites exist:
2130 2133
2131 2134 - The arguments are numbers or pairs of colon-separated numbers (like
2132 2135 1 4:8 9). These are interpreted as lines of previous input to be
2133 2136 loaded into the editor. The syntax is the same of the %macro command.
2134 2137
2135 2138 - If the argument doesn't start with a number, it is evaluated as a
2136 2139 variable and its contents loaded into the editor. You can thus edit
2137 2140 any string which contains python code (including the result of
2138 2141 previous edits).
2139 2142
2140 2143 - If the argument is the name of an object (other than a string),
2141 2144 IPython will try to locate the file where it was defined and open the
2142 2145 editor at the point where it is defined. You can use `%edit function`
2143 2146 to load an editor exactly at the point where 'function' is defined,
2144 2147 edit it and have the file be executed automatically.
2145 2148
2146 2149 If the object is a macro (see %macro for details), this opens up your
2147 2150 specified editor with a temporary file containing the macro's data.
2148 2151 Upon exit, the macro is reloaded with the contents of the file.
2149 2152
2150 2153 Note: opening at an exact line is only supported under Unix, and some
2151 2154 editors (like kedit and gedit up to Gnome 2.8) do not understand the
2152 2155 '+NUMBER' parameter necessary for this feature. Good editors like
2153 2156 (X)Emacs, vi, jed, pico and joe all do.
2154 2157
2155 2158 - If the argument is not found as a variable, IPython will look for a
2156 2159 file with that name (adding .py if necessary) and load it into the
2157 2160 editor. It will execute its contents with execfile() when you exit,
2158 2161 loading any code in the file into your interactive namespace.
2159 2162
2160 2163 After executing your code, %edit will return as output the code you
2161 2164 typed in the editor (except when it was an existing file). This way
2162 2165 you can reload the code in further invocations of %edit as a variable,
2163 2166 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
2164 2167 the output.
2165 2168
2166 2169 Note that %edit is also available through the alias %ed.
2167 2170
2168 2171 This is an example of creating a simple function inside the editor and
2169 2172 then modifying it. First, start up the editor:
2170 2173
2171 2174 In [1]: ed
2172 2175 Editing... done. Executing edited code...
2173 2176 Out[1]: 'def foo():n print "foo() was defined in an editing session"n'
2174 2177
2175 2178 We can then call the function foo():
2176 2179
2177 2180 In [2]: foo()
2178 2181 foo() was defined in an editing session
2179 2182
2180 2183 Now we edit foo. IPython automatically loads the editor with the
2181 2184 (temporary) file where foo() was previously defined:
2182 2185
2183 2186 In [3]: ed foo
2184 2187 Editing... done. Executing edited code...
2185 2188
2186 2189 And if we call foo() again we get the modified version:
2187 2190
2188 2191 In [4]: foo()
2189 2192 foo() has now been changed!
2190 2193
2191 2194 Here is an example of how to edit a code snippet successive
2192 2195 times. First we call the editor:
2193 2196
2194 2197 In [5]: ed
2195 2198 Editing... done. Executing edited code...
2196 2199 hello
2197 2200 Out[5]: "print 'hello'n"
2198 2201
2199 2202 Now we call it again with the previous output (stored in _):
2200 2203
2201 2204 In [6]: ed _
2202 2205 Editing... done. Executing edited code...
2203 2206 hello world
2204 2207 Out[6]: "print 'hello world'n"
2205 2208
2206 2209 Now we call it with the output #8 (stored in _8, also as Out[8]):
2207 2210
2208 2211 In [7]: ed _8
2209 2212 Editing... done. Executing edited code...
2210 2213 hello again
2211 2214 Out[7]: "print 'hello again'n"
2212 2215
2213 2216
2214 2217 Changing the default editor hook:
2215 2218
2216 2219 If you wish to write your own editor hook, you can put it in a
2217 2220 configuration file which you load at startup time. The default hook
2218 2221 is defined in the IPython.hooks module, and you can use that as a
2219 2222 starting example for further modifications. That file also has
2220 2223 general instructions on how to set a new hook for use once you've
2221 2224 defined it."""
2222 2225
2223 2226 # FIXME: This function has become a convoluted mess. It needs a
2224 2227 # ground-up rewrite with clean, simple logic.
2225 2228
2226 2229 def make_filename(arg):
2227 2230 "Make a filename from the given args"
2228 2231 try:
2229 2232 filename = get_py_filename(arg)
2230 2233 except IOError:
2231 2234 if args.endswith('.py'):
2232 2235 filename = arg
2233 2236 else:
2234 2237 filename = None
2235 2238 return filename
2236 2239
2237 2240 # custom exceptions
2238 2241 class DataIsObject(Exception): pass
2239 2242
2240 2243 opts,args = self.parse_options(parameter_s,'prxn:')
2241 2244 # Set a few locals from the options for convenience:
2242 2245 opts_p = opts.has_key('p')
2243 2246 opts_r = opts.has_key('r')
2244 2247
2245 2248 # Default line number value
2246 2249 lineno = opts.get('n',None)
2247 2250
2248 2251 if opts_p:
2249 2252 args = '_%s' % last_call[0]
2250 2253 if not self.shell.user_ns.has_key(args):
2251 2254 args = last_call[1]
2252 2255
2253 2256 # use last_call to remember the state of the previous call, but don't
2254 2257 # let it be clobbered by successive '-p' calls.
2255 2258 try:
2256 2259 last_call[0] = self.shell.outputcache.prompt_count
2257 2260 if not opts_p:
2258 2261 last_call[1] = parameter_s
2259 2262 except:
2260 2263 pass
2261 2264
2262 2265 # by default this is done with temp files, except when the given
2263 2266 # arg is a filename
2264 2267 use_temp = 1
2265 2268
2266 2269 if re.match(r'\d',args):
2267 2270 # Mode where user specifies ranges of lines, like in %macro.
2268 2271 # This means that you can't edit files whose names begin with
2269 2272 # numbers this way. Tough.
2270 2273 ranges = args.split()
2271 2274 data = ''.join(self.extract_input_slices(ranges,opts_r))
2272 2275 elif args.endswith('.py'):
2273 2276 filename = make_filename(args)
2274 2277 data = ''
2275 2278 use_temp = 0
2276 2279 elif args:
2277 2280 try:
2278 2281 # Load the parameter given as a variable. If not a string,
2279 2282 # process it as an object instead (below)
2280 2283
2281 2284 #print '*** args',args,'type',type(args) # dbg
2282 2285 data = eval(args,self.shell.user_ns)
2283 2286 if not type(data) in StringTypes:
2284 2287 raise DataIsObject
2285 2288
2286 2289 except (NameError,SyntaxError):
2287 2290 # given argument is not a variable, try as a filename
2288 2291 filename = make_filename(args)
2289 2292 if filename is None:
2290 2293 warn("Argument given (%s) can't be found as a variable "
2291 2294 "or as a filename." % args)
2292 2295 return
2293 2296
2294 2297 data = ''
2295 2298 use_temp = 0
2296 2299 except DataIsObject:
2297 2300
2298 2301 # macros have a special edit function
2299 2302 if isinstance(data,Macro):
2300 2303 self._edit_macro(args,data)
2301 2304 return
2302 2305
2303 2306 # For objects, try to edit the file where they are defined
2304 2307 try:
2305 2308 filename = inspect.getabsfile(data)
2306 2309 if 'fakemodule' in filename.lower() and inspect.isclass(data):
2307 2310 # class created by %edit? Try to find source
2308 2311 # by looking for method definitions instead, the
2309 2312 # __module__ in those classes is FakeModule.
2310 2313 attrs = [getattr(data, aname) for aname in dir(data)]
2311 2314 for attr in attrs:
2312 2315 if not inspect.ismethod(attr):
2313 2316 continue
2314 2317 filename = inspect.getabsfile(attr)
2315 2318 if filename and 'fakemodule' not in filename.lower():
2316 2319 # change the attribute to be the edit target instead
2317 2320 data = attr
2318 2321 break
2319 2322
2320 2323 datafile = 1
2321 2324 except TypeError:
2322 2325 filename = make_filename(args)
2323 2326 datafile = 1
2324 2327 warn('Could not find file where `%s` is defined.\n'
2325 2328 'Opening a file named `%s`' % (args,filename))
2326 2329 # Now, make sure we can actually read the source (if it was in
2327 2330 # a temp file it's gone by now).
2328 2331 if datafile:
2329 2332 try:
2330 2333 if lineno is None:
2331 2334 lineno = inspect.getsourcelines(data)[1]
2332 2335 except IOError:
2333 2336 filename = make_filename(args)
2334 2337 if filename is None:
2335 2338 warn('The file `%s` where `%s` was defined cannot '
2336 2339 'be read.' % (filename,data))
2337 2340 return
2338 2341 use_temp = 0
2339 2342 else:
2340 2343 data = ''
2341 2344
2342 2345 if use_temp:
2343 2346 filename = self.shell.mktempfile(data)
2344 2347 print 'IPython will make a temporary file named:',filename
2345 2348
2346 2349 # do actual editing here
2347 2350 print 'Editing...',
2348 2351 sys.stdout.flush()
2349 2352 self.shell.hooks.editor(filename,lineno)
2350 2353
2351 2354 # XXX TODO: should this be generalized for all string vars?
2352 2355 # For now, this is special-cased to blocks created by cpaste
2353 2356 if args.strip() == 'pasted_block':
2354 2357 self.shell.user_ns['pasted_block'] = file_read(filename)
2355 2358
2356 2359 if opts.has_key('x'): # -x prevents actual execution
2357 2360 print
2358 2361 else:
2359 2362 print 'done. Executing edited code...'
2360 2363 if opts_r:
2361 2364 self.shell.runlines(file_read(filename))
2362 2365 else:
2363 2366 self.shell.safe_execfile(filename,self.shell.user_ns,
2364 2367 self.shell.user_ns)
2365 2368
2366 2369
2367 2370 if use_temp:
2368 2371 try:
2369 2372 return open(filename).read()
2370 2373 except IOError,msg:
2371 2374 if msg.filename == filename:
2372 2375 warn('File not found. Did you forget to save?')
2373 2376 return
2374 2377 else:
2375 2378 self.shell.showtraceback()
2376 2379
2377 2380 def magic_xmode(self,parameter_s = ''):
2378 2381 """Switch modes for the exception handlers.
2379 2382
2380 2383 Valid modes: Plain, Context and Verbose.
2381 2384
2382 2385 If called without arguments, acts as a toggle."""
2383 2386
2384 2387 def xmode_switch_err(name):
2385 2388 warn('Error changing %s exception modes.\n%s' %
2386 2389 (name,sys.exc_info()[1]))
2387 2390
2388 2391 shell = self.shell
2389 2392 new_mode = parameter_s.strip().capitalize()
2390 2393 try:
2391 2394 shell.InteractiveTB.set_mode(mode=new_mode)
2392 2395 print 'Exception reporting mode:',shell.InteractiveTB.mode
2393 2396 except:
2394 2397 xmode_switch_err('user')
2395 2398
2396 2399 # threaded shells use a special handler in sys.excepthook
2397 2400 if shell.isthreaded:
2398 2401 try:
2399 2402 shell.sys_excepthook.set_mode(mode=new_mode)
2400 2403 except:
2401 2404 xmode_switch_err('threaded')
2402 2405
2403 2406 def magic_colors(self,parameter_s = ''):
2404 2407 """Switch color scheme for prompts, info system and exception handlers.
2405 2408
2406 2409 Currently implemented schemes: NoColor, Linux, LightBG.
2407 2410
2408 2411 Color scheme names are not case-sensitive."""
2409 2412
2410 2413 def color_switch_err(name):
2411 2414 warn('Error changing %s color schemes.\n%s' %
2412 2415 (name,sys.exc_info()[1]))
2413 2416
2414 2417
2415 2418 new_scheme = parameter_s.strip()
2416 2419 if not new_scheme:
2417 2420 raise UsageError(
2418 2421 "%colors: you must specify a color scheme. See '%colors?'")
2419 2422 return
2420 2423 # local shortcut
2421 2424 shell = self.shell
2422 2425
2423 2426 import IPython.rlineimpl as readline
2424 2427
2425 2428 if not readline.have_readline and sys.platform == "win32":
2426 2429 msg = """\
2427 2430 Proper color support under MS Windows requires the pyreadline library.
2428 2431 You can find it at:
2429 2432 http://ipython.scipy.org/moin/PyReadline/Intro
2430 2433 Gary's readline needs the ctypes module, from:
2431 2434 http://starship.python.net/crew/theller/ctypes
2432 2435 (Note that ctypes is already part of Python versions 2.5 and newer).
2433 2436
2434 2437 Defaulting color scheme to 'NoColor'"""
2435 2438 new_scheme = 'NoColor'
2436 2439 warn(msg)
2437 2440
2438 2441 # readline option is 0
2439 2442 if not shell.has_readline:
2440 2443 new_scheme = 'NoColor'
2441 2444
2442 2445 # Set prompt colors
2443 2446 try:
2444 2447 shell.outputcache.set_colors(new_scheme)
2445 2448 except:
2446 2449 color_switch_err('prompt')
2447 2450 else:
2448 2451 shell.rc.colors = \
2449 2452 shell.outputcache.color_table.active_scheme_name
2450 2453 # Set exception colors
2451 2454 try:
2452 2455 shell.InteractiveTB.set_colors(scheme = new_scheme)
2453 2456 shell.SyntaxTB.set_colors(scheme = new_scheme)
2454 2457 except:
2455 2458 color_switch_err('exception')
2456 2459
2457 2460 # threaded shells use a verbose traceback in sys.excepthook
2458 2461 if shell.isthreaded:
2459 2462 try:
2460 2463 shell.sys_excepthook.set_colors(scheme=new_scheme)
2461 2464 except:
2462 2465 color_switch_err('system exception handler')
2463 2466
2464 2467 # Set info (for 'object?') colors
2465 2468 if shell.rc.color_info:
2466 2469 try:
2467 2470 shell.inspector.set_active_scheme(new_scheme)
2468 2471 except:
2469 2472 color_switch_err('object inspector')
2470 2473 else:
2471 2474 shell.inspector.set_active_scheme('NoColor')
2472 2475
2473 2476 def magic_color_info(self,parameter_s = ''):
2474 2477 """Toggle color_info.
2475 2478
2476 2479 The color_info configuration parameter controls whether colors are
2477 2480 used for displaying object details (by things like %psource, %pfile or
2478 2481 the '?' system). This function toggles this value with each call.
2479 2482
2480 2483 Note that unless you have a fairly recent pager (less works better
2481 2484 than more) in your system, using colored object information displays
2482 2485 will not work properly. Test it and see."""
2483 2486
2484 2487 self.shell.rc.color_info = 1 - self.shell.rc.color_info
2485 2488 self.magic_colors(self.shell.rc.colors)
2486 2489 print 'Object introspection functions have now coloring:',
2487 2490 print ['OFF','ON'][self.shell.rc.color_info]
2488 2491
2489 2492 def magic_Pprint(self, parameter_s=''):
2490 2493 """Toggle pretty printing on/off."""
2491 2494
2492 2495 self.shell.rc.pprint = 1 - self.shell.rc.pprint
2493 2496 print 'Pretty printing has been turned', \
2494 2497 ['OFF','ON'][self.shell.rc.pprint]
2495 2498
2496 2499 def magic_exit(self, parameter_s=''):
2497 2500 """Exit IPython, confirming if configured to do so.
2498 2501
2499 2502 You can configure whether IPython asks for confirmation upon exit by
2500 2503 setting the confirm_exit flag in the ipythonrc file."""
2501 2504
2502 2505 self.shell.exit()
2503 2506
2504 2507 def magic_quit(self, parameter_s=''):
2505 2508 """Exit IPython, confirming if configured to do so (like %exit)"""
2506 2509
2507 2510 self.shell.exit()
2508 2511
2509 2512 def magic_Exit(self, parameter_s=''):
2510 2513 """Exit IPython without confirmation."""
2511 2514
2512 2515 self.shell.ask_exit()
2513 2516
2514 2517 #......................................................................
2515 2518 # Functions to implement unix shell-type things
2516 2519
2517 2520 @testdec.skip_doctest
2518 2521 def magic_alias(self, parameter_s = ''):
2519 2522 """Define an alias for a system command.
2520 2523
2521 2524 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
2522 2525
2523 2526 Then, typing 'alias_name params' will execute the system command 'cmd
2524 2527 params' (from your underlying operating system).
2525 2528
2526 2529 Aliases have lower precedence than magic functions and Python normal
2527 2530 variables, so if 'foo' is both a Python variable and an alias, the
2528 2531 alias can not be executed until 'del foo' removes the Python variable.
2529 2532
2530 2533 You can use the %l specifier in an alias definition to represent the
2531 2534 whole line when the alias is called. For example:
2532 2535
2533 2536 In [2]: alias all echo "Input in brackets: <%l>"
2534 2537 In [3]: all hello world
2535 2538 Input in brackets: <hello world>
2536 2539
2537 2540 You can also define aliases with parameters using %s specifiers (one
2538 2541 per parameter):
2539 2542
2540 2543 In [1]: alias parts echo first %s second %s
2541 2544 In [2]: %parts A B
2542 2545 first A second B
2543 2546 In [3]: %parts A
2544 2547 Incorrect number of arguments: 2 expected.
2545 2548 parts is an alias to: 'echo first %s second %s'
2546 2549
2547 2550 Note that %l and %s are mutually exclusive. You can only use one or
2548 2551 the other in your aliases.
2549 2552
2550 2553 Aliases expand Python variables just like system calls using ! or !!
2551 2554 do: all expressions prefixed with '$' get expanded. For details of
2552 2555 the semantic rules, see PEP-215:
2553 2556 http://www.python.org/peps/pep-0215.html. This is the library used by
2554 2557 IPython for variable expansion. If you want to access a true shell
2555 2558 variable, an extra $ is necessary to prevent its expansion by IPython:
2556 2559
2557 2560 In [6]: alias show echo
2558 2561 In [7]: PATH='A Python string'
2559 2562 In [8]: show $PATH
2560 2563 A Python string
2561 2564 In [9]: show $$PATH
2562 2565 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2563 2566
2564 2567 You can use the alias facility to acess all of $PATH. See the %rehash
2565 2568 and %rehashx functions, which automatically create aliases for the
2566 2569 contents of your $PATH.
2567 2570
2568 2571 If called with no parameters, %alias prints the current alias table."""
2569 2572
2570 2573 par = parameter_s.strip()
2571 2574 if not par:
2572 2575 stored = self.db.get('stored_aliases', {} )
2573 2576 atab = self.shell.alias_table
2574 2577 aliases = atab.keys()
2575 2578 aliases.sort()
2576 2579 res = []
2577 2580 showlast = []
2578 2581 for alias in aliases:
2579 2582 special = False
2580 2583 try:
2581 2584 tgt = atab[alias][1]
2582 2585 except (TypeError, AttributeError):
2583 2586 # unsubscriptable? probably a callable
2584 2587 tgt = atab[alias]
2585 2588 special = True
2586 2589 # 'interesting' aliases
2587 2590 if (alias in stored or
2588 2591 special or
2589 2592 alias.lower() != os.path.splitext(tgt)[0].lower() or
2590 2593 ' ' in tgt):
2591 2594 showlast.append((alias, tgt))
2592 2595 else:
2593 2596 res.append((alias, tgt ))
2594 2597
2595 2598 # show most interesting aliases last
2596 2599 res.extend(showlast)
2597 2600 print "Total number of aliases:",len(aliases)
2598 2601 return res
2599 2602 try:
2600 2603 alias,cmd = par.split(None,1)
2601 2604 except:
2602 2605 print OInspect.getdoc(self.magic_alias)
2603 2606 else:
2604 2607 nargs = cmd.count('%s')
2605 2608 if nargs>0 and cmd.find('%l')>=0:
2606 2609 error('The %s and %l specifiers are mutually exclusive '
2607 2610 'in alias definitions.')
2608 2611 else: # all looks OK
2609 2612 self.shell.alias_table[alias] = (nargs,cmd)
2610 2613 self.shell.alias_table_validate(verbose=0)
2611 2614 # end magic_alias
2612 2615
2613 2616 def magic_unalias(self, parameter_s = ''):
2614 2617 """Remove an alias"""
2615 2618
2616 2619 aname = parameter_s.strip()
2617 2620 if aname in self.shell.alias_table:
2618 2621 del self.shell.alias_table[aname]
2619 2622 stored = self.db.get('stored_aliases', {} )
2620 2623 if aname in stored:
2621 2624 print "Removing %stored alias",aname
2622 2625 del stored[aname]
2623 2626 self.db['stored_aliases'] = stored
2624 2627
2625 2628
2626 2629 def magic_rehashx(self, parameter_s = ''):
2627 2630 """Update the alias table with all executable files in $PATH.
2628 2631
2629 2632 This version explicitly checks that every entry in $PATH is a file
2630 2633 with execute access (os.X_OK), so it is much slower than %rehash.
2631 2634
2632 2635 Under Windows, it checks executability as a match agains a
2633 2636 '|'-separated string of extensions, stored in the IPython config
2634 2637 variable win_exec_ext. This defaults to 'exe|com|bat'.
2635 2638
2636 2639 This function also resets the root module cache of module completer,
2637 2640 used on slow filesystems.
2638 2641 """
2639 2642
2640 2643
2641 2644 ip = self.api
2642 2645
2643 2646 # for the benefit of module completer in ipy_completers.py
2644 2647 del ip.db['rootmodules']
2645 2648
2646 2649 path = [os.path.abspath(os.path.expanduser(p)) for p in
2647 2650 os.environ.get('PATH','').split(os.pathsep)]
2648 2651 path = filter(os.path.isdir,path)
2649 2652
2650 2653 alias_table = self.shell.alias_table
2651 2654 syscmdlist = []
2652 2655 if os.name == 'posix':
2653 2656 isexec = lambda fname:os.path.isfile(fname) and \
2654 2657 os.access(fname,os.X_OK)
2655 2658 else:
2656 2659
2657 2660 try:
2658 2661 winext = os.environ['pathext'].replace(';','|').replace('.','')
2659 2662 except KeyError:
2660 2663 winext = 'exe|com|bat|py'
2661 2664 if 'py' not in winext:
2662 2665 winext += '|py'
2663 2666 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2664 2667 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2665 2668 savedir = os.getcwd()
2666 2669 try:
2667 2670 # write the whole loop for posix/Windows so we don't have an if in
2668 2671 # the innermost part
2669 2672 if os.name == 'posix':
2670 2673 for pdir in path:
2671 2674 os.chdir(pdir)
2672 2675 for ff in os.listdir(pdir):
2673 2676 if isexec(ff) and ff not in self.shell.no_alias:
2674 2677 # each entry in the alias table must be (N,name),
2675 2678 # where N is the number of positional arguments of the
2676 2679 # alias.
2677 2680 # Dots will be removed from alias names, since ipython
2678 2681 # assumes names with dots to be python code
2679 2682 alias_table[ff.replace('.','')] = (0,ff)
2680 2683 syscmdlist.append(ff)
2681 2684 else:
2682 2685 for pdir in path:
2683 2686 os.chdir(pdir)
2684 2687 for ff in os.listdir(pdir):
2685 2688 base, ext = os.path.splitext(ff)
2686 2689 if isexec(ff) and base.lower() not in self.shell.no_alias:
2687 2690 if ext.lower() == '.exe':
2688 2691 ff = base
2689 2692 alias_table[base.lower().replace('.','')] = (0,ff)
2690 2693 syscmdlist.append(ff)
2691 2694 # Make sure the alias table doesn't contain keywords or builtins
2692 2695 self.shell.alias_table_validate()
2693 2696 # Call again init_auto_alias() so we get 'rm -i' and other
2694 2697 # modified aliases since %rehashx will probably clobber them
2695 2698
2696 2699 # no, we don't want them. if %rehashx clobbers them, good,
2697 2700 # we'll probably get better versions
2698 2701 # self.shell.init_auto_alias()
2699 2702 db = ip.db
2700 2703 db['syscmdlist'] = syscmdlist
2701 2704 finally:
2702 2705 os.chdir(savedir)
2703 2706
2704 2707 def magic_pwd(self, parameter_s = ''):
2705 2708 """Return the current working directory path."""
2706 2709 return os.getcwd()
2707 2710
2708 2711 def magic_cd(self, parameter_s=''):
2709 2712 """Change the current working directory.
2710 2713
2711 2714 This command automatically maintains an internal list of directories
2712 2715 you visit during your IPython session, in the variable _dh. The
2713 2716 command %dhist shows this history nicely formatted. You can also
2714 2717 do 'cd -<tab>' to see directory history conveniently.
2715 2718
2716 2719 Usage:
2717 2720
2718 2721 cd 'dir': changes to directory 'dir'.
2719 2722
2720 2723 cd -: changes to the last visited directory.
2721 2724
2722 2725 cd -<n>: changes to the n-th directory in the directory history.
2723 2726
2724 2727 cd --foo: change to directory that matches 'foo' in history
2725 2728
2726 2729 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
2727 2730 (note: cd <bookmark_name> is enough if there is no
2728 2731 directory <bookmark_name>, but a bookmark with the name exists.)
2729 2732 'cd -b <tab>' allows you to tab-complete bookmark names.
2730 2733
2731 2734 Options:
2732 2735
2733 2736 -q: quiet. Do not print the working directory after the cd command is
2734 2737 executed. By default IPython's cd command does print this directory,
2735 2738 since the default prompts do not display path information.
2736 2739
2737 2740 Note that !cd doesn't work for this purpose because the shell where
2738 2741 !command runs is immediately discarded after executing 'command'."""
2739 2742
2740 2743 parameter_s = parameter_s.strip()
2741 2744 #bkms = self.shell.persist.get("bookmarks",{})
2742 2745
2743 2746 oldcwd = os.getcwd()
2744 2747 numcd = re.match(r'(-)(\d+)$',parameter_s)
2745 2748 # jump in directory history by number
2746 2749 if numcd:
2747 2750 nn = int(numcd.group(2))
2748 2751 try:
2749 2752 ps = self.shell.user_ns['_dh'][nn]
2750 2753 except IndexError:
2751 2754 print 'The requested directory does not exist in history.'
2752 2755 return
2753 2756 else:
2754 2757 opts = {}
2755 2758 elif parameter_s.startswith('--'):
2756 2759 ps = None
2757 2760 fallback = None
2758 2761 pat = parameter_s[2:]
2759 2762 dh = self.shell.user_ns['_dh']
2760 2763 # first search only by basename (last component)
2761 2764 for ent in reversed(dh):
2762 2765 if pat in os.path.basename(ent) and os.path.isdir(ent):
2763 2766 ps = ent
2764 2767 break
2765 2768
2766 2769 if fallback is None and pat in ent and os.path.isdir(ent):
2767 2770 fallback = ent
2768 2771
2769 2772 # if we have no last part match, pick the first full path match
2770 2773 if ps is None:
2771 2774 ps = fallback
2772 2775
2773 2776 if ps is None:
2774 2777 print "No matching entry in directory history"
2775 2778 return
2776 2779 else:
2777 2780 opts = {}
2778 2781
2779 2782
2780 2783 else:
2781 2784 #turn all non-space-escaping backslashes to slashes,
2782 2785 # for c:\windows\directory\names\
2783 2786 parameter_s = re.sub(r'\\(?! )','/', parameter_s)
2784 2787 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
2785 2788 # jump to previous
2786 2789 if ps == '-':
2787 2790 try:
2788 2791 ps = self.shell.user_ns['_dh'][-2]
2789 2792 except IndexError:
2790 2793 raise UsageError('%cd -: No previous directory to change to.')
2791 2794 # jump to bookmark if needed
2792 2795 else:
2793 2796 if not os.path.isdir(ps) or opts.has_key('b'):
2794 2797 bkms = self.db.get('bookmarks', {})
2795 2798
2796 2799 if bkms.has_key(ps):
2797 2800 target = bkms[ps]
2798 2801 print '(bookmark:%s) -> %s' % (ps,target)
2799 2802 ps = target
2800 2803 else:
2801 2804 if opts.has_key('b'):
2802 2805 raise UsageError("Bookmark '%s' not found. "
2803 2806 "Use '%%bookmark -l' to see your bookmarks." % ps)
2804 2807
2805 2808 # at this point ps should point to the target dir
2806 2809 if ps:
2807 2810 try:
2808 2811 os.chdir(os.path.expanduser(ps))
2809 2812 if self.shell.rc.term_title:
2810 2813 #print 'set term title:',self.shell.rc.term_title # dbg
2811 2814 platutils.set_term_title('IPy ' + abbrev_cwd())
2812 2815 except OSError:
2813 2816 print sys.exc_info()[1]
2814 2817 else:
2815 2818 cwd = os.getcwd()
2816 2819 dhist = self.shell.user_ns['_dh']
2817 2820 if oldcwd != cwd:
2818 2821 dhist.append(cwd)
2819 2822 self.db['dhist'] = compress_dhist(dhist)[-100:]
2820 2823
2821 2824 else:
2822 2825 os.chdir(self.shell.home_dir)
2823 2826 if self.shell.rc.term_title:
2824 2827 platutils.set_term_title("IPy ~")
2825 2828 cwd = os.getcwd()
2826 2829 dhist = self.shell.user_ns['_dh']
2827 2830
2828 2831 if oldcwd != cwd:
2829 2832 dhist.append(cwd)
2830 2833 self.db['dhist'] = compress_dhist(dhist)[-100:]
2831 2834 if not 'q' in opts and self.shell.user_ns['_dh']:
2832 2835 print self.shell.user_ns['_dh'][-1]
2833 2836
2834 2837
2835 2838 def magic_env(self, parameter_s=''):
2836 2839 """List environment variables."""
2837 2840
2838 2841 return os.environ.data
2839 2842
2840 2843 def magic_pushd(self, parameter_s=''):
2841 2844 """Place the current dir on stack and change directory.
2842 2845
2843 2846 Usage:\\
2844 2847 %pushd ['dirname']
2845 2848 """
2846 2849
2847 2850 dir_s = self.shell.dir_stack
2848 2851 tgt = os.path.expanduser(parameter_s)
2849 2852 cwd = os.getcwd().replace(self.home_dir,'~')
2850 2853 if tgt:
2851 2854 self.magic_cd(parameter_s)
2852 2855 dir_s.insert(0,cwd)
2853 2856 return self.magic_dirs()
2854 2857
2855 2858 def magic_popd(self, parameter_s=''):
2856 2859 """Change to directory popped off the top of the stack.
2857 2860 """
2858 2861 if not self.shell.dir_stack:
2859 2862 raise UsageError("%popd on empty stack")
2860 2863 top = self.shell.dir_stack.pop(0)
2861 2864 self.magic_cd(top)
2862 2865 print "popd ->",top
2863 2866
2864 2867 def magic_dirs(self, parameter_s=''):
2865 2868 """Return the current directory stack."""
2866 2869
2867 2870 return self.shell.dir_stack
2868 2871
2869 2872 def magic_dhist(self, parameter_s=''):
2870 2873 """Print your history of visited directories.
2871 2874
2872 2875 %dhist -> print full history\\
2873 2876 %dhist n -> print last n entries only\\
2874 2877 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
2875 2878
2876 2879 This history is automatically maintained by the %cd command, and
2877 2880 always available as the global list variable _dh. You can use %cd -<n>
2878 2881 to go to directory number <n>.
2879 2882
2880 2883 Note that most of time, you should view directory history by entering
2881 2884 cd -<TAB>.
2882 2885
2883 2886 """
2884 2887
2885 2888 dh = self.shell.user_ns['_dh']
2886 2889 if parameter_s:
2887 2890 try:
2888 2891 args = map(int,parameter_s.split())
2889 2892 except:
2890 2893 self.arg_err(Magic.magic_dhist)
2891 2894 return
2892 2895 if len(args) == 1:
2893 2896 ini,fin = max(len(dh)-(args[0]),0),len(dh)
2894 2897 elif len(args) == 2:
2895 2898 ini,fin = args
2896 2899 else:
2897 2900 self.arg_err(Magic.magic_dhist)
2898 2901 return
2899 2902 else:
2900 2903 ini,fin = 0,len(dh)
2901 2904 nlprint(dh,
2902 2905 header = 'Directory history (kept in _dh)',
2903 2906 start=ini,stop=fin)
2904 2907
2905 2908 @testdec.skip_doctest
2906 2909 def magic_sc(self, parameter_s=''):
2907 2910 """Shell capture - execute a shell command and capture its output.
2908 2911
2909 2912 DEPRECATED. Suboptimal, retained for backwards compatibility.
2910 2913
2911 2914 You should use the form 'var = !command' instead. Example:
2912 2915
2913 2916 "%sc -l myfiles = ls ~" should now be written as
2914 2917
2915 2918 "myfiles = !ls ~"
2916 2919
2917 2920 myfiles.s, myfiles.l and myfiles.n still apply as documented
2918 2921 below.
2919 2922
2920 2923 --
2921 2924 %sc [options] varname=command
2922 2925
2923 2926 IPython will run the given command using commands.getoutput(), and
2924 2927 will then update the user's interactive namespace with a variable
2925 2928 called varname, containing the value of the call. Your command can
2926 2929 contain shell wildcards, pipes, etc.
2927 2930
2928 2931 The '=' sign in the syntax is mandatory, and the variable name you
2929 2932 supply must follow Python's standard conventions for valid names.
2930 2933
2931 2934 (A special format without variable name exists for internal use)
2932 2935
2933 2936 Options:
2934 2937
2935 2938 -l: list output. Split the output on newlines into a list before
2936 2939 assigning it to the given variable. By default the output is stored
2937 2940 as a single string.
2938 2941
2939 2942 -v: verbose. Print the contents of the variable.
2940 2943
2941 2944 In most cases you should not need to split as a list, because the
2942 2945 returned value is a special type of string which can automatically
2943 2946 provide its contents either as a list (split on newlines) or as a
2944 2947 space-separated string. These are convenient, respectively, either
2945 2948 for sequential processing or to be passed to a shell command.
2946 2949
2947 2950 For example:
2948 2951
2949 2952 # all-random
2950 2953
2951 2954 # Capture into variable a
2952 2955 In [1]: sc a=ls *py
2953 2956
2954 2957 # a is a string with embedded newlines
2955 2958 In [2]: a
2956 2959 Out[2]: 'setup.py\\nwin32_manual_post_install.py'
2957 2960
2958 2961 # which can be seen as a list:
2959 2962 In [3]: a.l
2960 2963 Out[3]: ['setup.py', 'win32_manual_post_install.py']
2961 2964
2962 2965 # or as a whitespace-separated string:
2963 2966 In [4]: a.s
2964 2967 Out[4]: 'setup.py win32_manual_post_install.py'
2965 2968
2966 2969 # a.s is useful to pass as a single command line:
2967 2970 In [5]: !wc -l $a.s
2968 2971 146 setup.py
2969 2972 130 win32_manual_post_install.py
2970 2973 276 total
2971 2974
2972 2975 # while the list form is useful to loop over:
2973 2976 In [6]: for f in a.l:
2974 2977 ...: !wc -l $f
2975 2978 ...:
2976 2979 146 setup.py
2977 2980 130 win32_manual_post_install.py
2978 2981
2979 2982 Similiarly, the lists returned by the -l option are also special, in
2980 2983 the sense that you can equally invoke the .s attribute on them to
2981 2984 automatically get a whitespace-separated string from their contents:
2982 2985
2983 2986 In [7]: sc -l b=ls *py
2984 2987
2985 2988 In [8]: b
2986 2989 Out[8]: ['setup.py', 'win32_manual_post_install.py']
2987 2990
2988 2991 In [9]: b.s
2989 2992 Out[9]: 'setup.py win32_manual_post_install.py'
2990 2993
2991 2994 In summary, both the lists and strings used for ouptut capture have
2992 2995 the following special attributes:
2993 2996
2994 2997 .l (or .list) : value as list.
2995 2998 .n (or .nlstr): value as newline-separated string.
2996 2999 .s (or .spstr): value as space-separated string.
2997 3000 """
2998 3001
2999 3002 opts,args = self.parse_options(parameter_s,'lv')
3000 3003 # Try to get a variable name and command to run
3001 3004 try:
3002 3005 # the variable name must be obtained from the parse_options
3003 3006 # output, which uses shlex.split to strip options out.
3004 3007 var,_ = args.split('=',1)
3005 3008 var = var.strip()
3006 3009 # But the the command has to be extracted from the original input
3007 3010 # parameter_s, not on what parse_options returns, to avoid the
3008 3011 # quote stripping which shlex.split performs on it.
3009 3012 _,cmd = parameter_s.split('=',1)
3010 3013 except ValueError:
3011 3014 var,cmd = '',''
3012 3015 # If all looks ok, proceed
3013 3016 out,err = self.shell.getoutputerror(cmd)
3014 3017 if err:
3015 3018 print >> Term.cerr,err
3016 3019 if opts.has_key('l'):
3017 3020 out = SList(out.split('\n'))
3018 3021 else:
3019 3022 out = LSString(out)
3020 3023 if opts.has_key('v'):
3021 3024 print '%s ==\n%s' % (var,pformat(out))
3022 3025 if var:
3023 3026 self.shell.user_ns.update({var:out})
3024 3027 else:
3025 3028 return out
3026 3029
3027 3030 def magic_sx(self, parameter_s=''):
3028 3031 """Shell execute - run a shell command and capture its output.
3029 3032
3030 3033 %sx command
3031 3034
3032 3035 IPython will run the given command using commands.getoutput(), and
3033 3036 return the result formatted as a list (split on '\\n'). Since the
3034 3037 output is _returned_, it will be stored in ipython's regular output
3035 3038 cache Out[N] and in the '_N' automatic variables.
3036 3039
3037 3040 Notes:
3038 3041
3039 3042 1) If an input line begins with '!!', then %sx is automatically
3040 3043 invoked. That is, while:
3041 3044 !ls
3042 3045 causes ipython to simply issue system('ls'), typing
3043 3046 !!ls
3044 3047 is a shorthand equivalent to:
3045 3048 %sx ls
3046 3049
3047 3050 2) %sx differs from %sc in that %sx automatically splits into a list,
3048 3051 like '%sc -l'. The reason for this is to make it as easy as possible
3049 3052 to process line-oriented shell output via further python commands.
3050 3053 %sc is meant to provide much finer control, but requires more
3051 3054 typing.
3052 3055
3053 3056 3) Just like %sc -l, this is a list with special attributes:
3054 3057
3055 3058 .l (or .list) : value as list.
3056 3059 .n (or .nlstr): value as newline-separated string.
3057 3060 .s (or .spstr): value as whitespace-separated string.
3058 3061
3059 3062 This is very useful when trying to use such lists as arguments to
3060 3063 system commands."""
3061 3064
3062 3065 if parameter_s:
3063 3066 out,err = self.shell.getoutputerror(parameter_s)
3064 3067 if err:
3065 3068 print >> Term.cerr,err
3066 3069 return SList(out.split('\n'))
3067 3070
3068 3071 def magic_bg(self, parameter_s=''):
3069 3072 """Run a job in the background, in a separate thread.
3070 3073
3071 3074 For example,
3072 3075
3073 3076 %bg myfunc(x,y,z=1)
3074 3077
3075 3078 will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the
3076 3079 execution starts, a message will be printed indicating the job
3077 3080 number. If your job number is 5, you can use
3078 3081
3079 3082 myvar = jobs.result(5) or myvar = jobs[5].result
3080 3083
3081 3084 to assign this result to variable 'myvar'.
3082 3085
3083 3086 IPython has a job manager, accessible via the 'jobs' object. You can
3084 3087 type jobs? to get more information about it, and use jobs.<TAB> to see
3085 3088 its attributes. All attributes not starting with an underscore are
3086 3089 meant for public use.
3087 3090
3088 3091 In particular, look at the jobs.new() method, which is used to create
3089 3092 new jobs. This magic %bg function is just a convenience wrapper
3090 3093 around jobs.new(), for expression-based jobs. If you want to create a
3091 3094 new job with an explicit function object and arguments, you must call
3092 3095 jobs.new() directly.
3093 3096
3094 3097 The jobs.new docstring also describes in detail several important
3095 3098 caveats associated with a thread-based model for background job
3096 3099 execution. Type jobs.new? for details.
3097 3100
3098 3101 You can check the status of all jobs with jobs.status().
3099 3102
3100 3103 The jobs variable is set by IPython into the Python builtin namespace.
3101 3104 If you ever declare a variable named 'jobs', you will shadow this
3102 3105 name. You can either delete your global jobs variable to regain
3103 3106 access to the job manager, or make a new name and assign it manually
3104 3107 to the manager (stored in IPython's namespace). For example, to
3105 3108 assign the job manager to the Jobs name, use:
3106 3109
3107 3110 Jobs = __builtins__.jobs"""
3108 3111
3109 3112 self.shell.jobs.new(parameter_s,self.shell.user_ns)
3110 3113
3111 3114 def magic_r(self, parameter_s=''):
3112 3115 """Repeat previous input.
3113 3116
3114 3117 Note: Consider using the more powerfull %rep instead!
3115 3118
3116 3119 If given an argument, repeats the previous command which starts with
3117 3120 the same string, otherwise it just repeats the previous input.
3118 3121
3119 3122 Shell escaped commands (with ! as first character) are not recognized
3120 3123 by this system, only pure python code and magic commands.
3121 3124 """
3122 3125
3123 3126 start = parameter_s.strip()
3124 3127 esc_magic = self.shell.ESC_MAGIC
3125 3128 # Identify magic commands even if automagic is on (which means
3126 3129 # the in-memory version is different from that typed by the user).
3127 3130 if self.shell.rc.automagic:
3128 3131 start_magic = esc_magic+start
3129 3132 else:
3130 3133 start_magic = start
3131 3134 # Look through the input history in reverse
3132 3135 for n in range(len(self.shell.input_hist)-2,0,-1):
3133 3136 input = self.shell.input_hist[n]
3134 3137 # skip plain 'r' lines so we don't recurse to infinity
3135 3138 if input != '_ip.magic("r")\n' and \
3136 3139 (input.startswith(start) or input.startswith(start_magic)):
3137 3140 #print 'match',`input` # dbg
3138 3141 print 'Executing:',input,
3139 3142 self.shell.runlines(input)
3140 3143 return
3141 3144 print 'No previous input matching `%s` found.' % start
3142 3145
3143 3146
3144 3147 def magic_bookmark(self, parameter_s=''):
3145 3148 """Manage IPython's bookmark system.
3146 3149
3147 3150 %bookmark <name> - set bookmark to current dir
3148 3151 %bookmark <name> <dir> - set bookmark to <dir>
3149 3152 %bookmark -l - list all bookmarks
3150 3153 %bookmark -d <name> - remove bookmark
3151 3154 %bookmark -r - remove all bookmarks
3152 3155
3153 3156 You can later on access a bookmarked folder with:
3154 3157 %cd -b <name>
3155 3158 or simply '%cd <name>' if there is no directory called <name> AND
3156 3159 there is such a bookmark defined.
3157 3160
3158 3161 Your bookmarks persist through IPython sessions, but they are
3159 3162 associated with each profile."""
3160 3163
3161 3164 opts,args = self.parse_options(parameter_s,'drl',mode='list')
3162 3165 if len(args) > 2:
3163 3166 raise UsageError("%bookmark: too many arguments")
3164 3167
3165 3168 bkms = self.db.get('bookmarks',{})
3166 3169
3167 3170 if opts.has_key('d'):
3168 3171 try:
3169 3172 todel = args[0]
3170 3173 except IndexError:
3171 3174 raise UsageError(
3172 3175 "%bookmark -d: must provide a bookmark to delete")
3173 3176 else:
3174 3177 try:
3175 3178 del bkms[todel]
3176 3179 except KeyError:
3177 3180 raise UsageError(
3178 3181 "%%bookmark -d: Can't delete bookmark '%s'" % todel)
3179 3182
3180 3183 elif opts.has_key('r'):
3181 3184 bkms = {}
3182 3185 elif opts.has_key('l'):
3183 3186 bks = bkms.keys()
3184 3187 bks.sort()
3185 3188 if bks:
3186 3189 size = max(map(len,bks))
3187 3190 else:
3188 3191 size = 0
3189 3192 fmt = '%-'+str(size)+'s -> %s'
3190 3193 print 'Current bookmarks:'
3191 3194 for bk in bks:
3192 3195 print fmt % (bk,bkms[bk])
3193 3196 else:
3194 3197 if not args:
3195 3198 raise UsageError("%bookmark: You must specify the bookmark name")
3196 3199 elif len(args)==1:
3197 3200 bkms[args[0]] = os.getcwd()
3198 3201 elif len(args)==2:
3199 3202 bkms[args[0]] = args[1]
3200 3203 self.db['bookmarks'] = bkms
3201 3204
3202 3205 def magic_pycat(self, parameter_s=''):
3203 3206 """Show a syntax-highlighted file through a pager.
3204 3207
3205 3208 This magic is similar to the cat utility, but it will assume the file
3206 3209 to be Python source and will show it with syntax highlighting. """
3207 3210
3208 3211 try:
3209 3212 filename = get_py_filename(parameter_s)
3210 3213 cont = file_read(filename)
3211 3214 except IOError:
3212 3215 try:
3213 3216 cont = eval(parameter_s,self.user_ns)
3214 3217 except NameError:
3215 3218 cont = None
3216 3219 if cont is None:
3217 3220 print "Error: no such file or variable"
3218 3221 return
3219 3222
3220 3223 page(self.shell.pycolorize(cont),
3221 3224 screen_lines=self.shell.rc.screen_length)
3222 3225
3223 3226 def magic_cpaste(self, parameter_s=''):
3224 3227 """Allows you to paste & execute a pre-formatted code block from clipboard.
3225 3228
3226 3229 You must terminate the block with '--' (two minus-signs) alone on the
3227 3230 line. You can also provide your own sentinel with '%paste -s %%' ('%%'
3228 3231 is the new sentinel for this operation)
3229 3232
3230 3233 The block is dedented prior to execution to enable execution of method
3231 3234 definitions. '>' and '+' characters at the beginning of a line are
3232 3235 ignored, to allow pasting directly from e-mails, diff files and
3233 3236 doctests (the '...' continuation prompt is also stripped). The
3234 3237 executed block is also assigned to variable named 'pasted_block' for
3235 3238 later editing with '%edit pasted_block'.
3236 3239
3237 3240 You can also pass a variable name as an argument, e.g. '%cpaste foo'.
3238 3241 This assigns the pasted block to variable 'foo' as string, without
3239 3242 dedenting or executing it (preceding >>> and + is still stripped)
3240 3243
3241 3244 '%cpaste -r' re-executes the block previously entered by cpaste.
3242 3245
3243 3246 Do not be alarmed by garbled output on Windows (it's a readline bug).
3244 3247 Just press enter and type -- (and press enter again) and the block
3245 3248 will be what was just pasted.
3246 3249
3247 3250 IPython statements (magics, shell escapes) are not supported (yet).
3248 3251 """
3249 3252 opts,args = self.parse_options(parameter_s,'rs:',mode='string')
3250 3253 par = args.strip()
3251 3254 if opts.has_key('r'):
3252 3255 b = self.user_ns.get('pasted_block', None)
3253 3256 if b is None:
3254 3257 raise UsageError('No previous pasted block available')
3255 3258 print "Re-executing '%s...' (%d chars)"% (b.split('\n',1)[0], len(b))
3256 3259 exec b in self.user_ns
3257 3260 return
3258 3261
3259 3262 sentinel = opts.get('s','--')
3260 3263
3261 3264 # Regular expressions that declare text we strip from the input:
3262 3265 strip_re = [r'^\s*In \[\d+\]:', # IPython input prompt
3263 3266 r'^\s*(\s?>)+', # Python input prompt
3264 3267 r'^\s*\.{3,}', # Continuation prompts
3265 3268 r'^\++',
3266 3269 ]
3267 3270
3268 3271 strip_from_start = map(re.compile,strip_re)
3269 3272
3270 3273 from IPython import iplib
3271 3274 lines = []
3272 3275 print "Pasting code; enter '%s' alone on the line to stop." % sentinel
3273 3276 while 1:
3274 3277 l = iplib.raw_input_original(':')
3275 3278 if l ==sentinel:
3276 3279 break
3277 3280
3278 3281 for pat in strip_from_start:
3279 3282 l = pat.sub('',l)
3280 3283 lines.append(l)
3281 3284
3282 3285 block = "\n".join(lines) + '\n'
3283 3286 #print "block:\n",block
3284 3287 if not par:
3285 3288 b = textwrap.dedent(block)
3286 3289 self.user_ns['pasted_block'] = b
3287 3290 exec b in self.user_ns
3288 3291 else:
3289 3292 self.user_ns[par] = SList(block.splitlines())
3290 3293 print "Block assigned to '%s'" % par
3291 3294
3292 3295 def magic_quickref(self,arg):
3293 3296 """ Show a quick reference sheet """
3294 3297 import IPython.usage
3295 3298 qr = IPython.usage.quick_reference + self.magic_magic('-brief')
3296 3299
3297 3300 page(qr)
3298 3301
3299 3302 def magic_upgrade(self,arg):
3300 3303 """ Upgrade your IPython installation
3301 3304
3302 3305 This will copy the config files that don't yet exist in your
3303 3306 ipython dir from the system config dir. Use this after upgrading
3304 3307 IPython if you don't wish to delete your .ipython dir.
3305 3308
3306 3309 Call with -nolegacy to get rid of ipythonrc* files (recommended for
3307 3310 new users)
3308 3311
3309 3312 """
3310 3313 ip = self.getapi()
3311 3314 ipinstallation = path(IPython.__file__).dirname()
3312 3315 upgrade_script = '%s "%s"' % (sys.executable,ipinstallation / 'upgrade_dir.py')
3313 3316 src_config = ipinstallation / 'UserConfig'
3314 3317 userdir = path(ip.options.ipythondir)
3315 3318 cmd = '%s "%s" "%s"' % (upgrade_script, src_config, userdir)
3316 3319 print ">",cmd
3317 3320 shell(cmd)
3318 3321 if arg == '-nolegacy':
3319 3322 legacy = userdir.files('ipythonrc*')
3320 3323 print "Nuking legacy files:",legacy
3321 3324
3322 3325 [p.remove() for p in legacy]
3323 3326 suffix = (sys.platform == 'win32' and '.ini' or '')
3324 3327 (userdir / ('ipythonrc' + suffix)).write_text('# Empty, see ipy_user_conf.py\n')
3325 3328
3326 3329
3327 3330 def magic_doctest_mode(self,parameter_s=''):
3328 3331 """Toggle doctest mode on and off.
3329 3332
3330 3333 This mode allows you to toggle the prompt behavior between normal
3331 3334 IPython prompts and ones that are as similar to the default IPython
3332 3335 interpreter as possible.
3333 3336
3334 3337 It also supports the pasting of code snippets that have leading '>>>'
3335 3338 and '...' prompts in them. This means that you can paste doctests from
3336 3339 files or docstrings (even if they have leading whitespace), and the
3337 3340 code will execute correctly. You can then use '%history -tn' to see
3338 3341 the translated history without line numbers; this will give you the
3339 3342 input after removal of all the leading prompts and whitespace, which
3340 3343 can be pasted back into an editor.
3341 3344
3342 3345 With these features, you can switch into this mode easily whenever you
3343 3346 need to do testing and changes to doctests, without having to leave
3344 3347 your existing IPython session.
3345 3348 """
3346 3349
3347 3350 # XXX - Fix this to have cleaner activate/deactivate calls.
3348 3351 from IPython.Extensions import InterpreterPasteInput as ipaste
3349 3352 from IPython.ipstruct import Struct
3350 3353
3351 3354 # Shorthands
3352 3355 shell = self.shell
3353 3356 oc = shell.outputcache
3354 3357 rc = shell.rc
3355 3358 meta = shell.meta
3356 3359 # dstore is a data store kept in the instance metadata bag to track any
3357 3360 # changes we make, so we can undo them later.
3358 3361 dstore = meta.setdefault('doctest_mode',Struct())
3359 3362 save_dstore = dstore.setdefault
3360 3363
3361 3364 # save a few values we'll need to recover later
3362 3365 mode = save_dstore('mode',False)
3363 3366 save_dstore('rc_pprint',rc.pprint)
3364 3367 save_dstore('xmode',shell.InteractiveTB.mode)
3365 3368 save_dstore('rc_separate_out',rc.separate_out)
3366 3369 save_dstore('rc_separate_out2',rc.separate_out2)
3367 3370 save_dstore('rc_prompts_pad_left',rc.prompts_pad_left)
3368 3371 save_dstore('rc_separate_in',rc.separate_in)
3369 3372
3370 3373 if mode == False:
3371 3374 # turn on
3372 3375 ipaste.activate_prefilter()
3373 3376
3374 3377 oc.prompt1.p_template = '>>> '
3375 3378 oc.prompt2.p_template = '... '
3376 3379 oc.prompt_out.p_template = ''
3377 3380
3378 3381 # Prompt separators like plain python
3379 3382 oc.input_sep = oc.prompt1.sep = ''
3380 3383 oc.output_sep = ''
3381 3384 oc.output_sep2 = ''
3382 3385
3383 3386 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3384 3387 oc.prompt_out.pad_left = False
3385 3388
3386 3389 rc.pprint = False
3387 3390
3388 3391 shell.magic_xmode('Plain')
3389 3392
3390 3393 else:
3391 3394 # turn off
3392 3395 ipaste.deactivate_prefilter()
3393 3396
3394 3397 oc.prompt1.p_template = rc.prompt_in1
3395 3398 oc.prompt2.p_template = rc.prompt_in2
3396 3399 oc.prompt_out.p_template = rc.prompt_out
3397 3400
3398 3401 oc.input_sep = oc.prompt1.sep = dstore.rc_separate_in
3399 3402
3400 3403 oc.output_sep = dstore.rc_separate_out
3401 3404 oc.output_sep2 = dstore.rc_separate_out2
3402 3405
3403 3406 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3404 3407 oc.prompt_out.pad_left = dstore.rc_prompts_pad_left
3405 3408
3406 3409 rc.pprint = dstore.rc_pprint
3407 3410
3408 3411 shell.magic_xmode(dstore.xmode)
3409 3412
3410 3413 # Store new mode and inform
3411 3414 dstore.mode = bool(1-int(mode))
3412 3415 print 'Doctest mode is:',
3413 3416 print ['OFF','ON'][dstore.mode]
3414 3417
3415 3418 # end Magic
@@ -1,2679 +1,2729 b''
1 1 # -*- coding: utf-8 -*-
2 2 """
3 3 IPython -- An enhanced Interactive Python
4 4
5 5 Requires Python 2.4 or newer.
6 6
7 7 This file contains all the classes and helper functions specific to IPython.
8 8 """
9 9
10 10 #*****************************************************************************
11 11 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
12 12 # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu>
13 13 #
14 14 # Distributed under the terms of the BSD License. The full license is in
15 15 # the file COPYING, distributed as part of this software.
16 16 #
17 17 # Note: this code originally subclassed code.InteractiveConsole from the
18 18 # Python standard library. Over time, all of that class has been copied
19 19 # verbatim here for modifications which could not be accomplished by
20 20 # subclassing. At this point, there are no dependencies at all on the code
21 21 # module anymore (it is not even imported). The Python License (sec. 2)
22 22 # allows for this, but it's always nice to acknowledge credit where credit is
23 23 # due.
24 24 #*****************************************************************************
25 25
26 26 #****************************************************************************
27 27 # Modules and globals
28 28
29 29 # Python standard modules
30 30 import __main__
31 31 import __builtin__
32 32 import StringIO
33 33 import bdb
34 34 import cPickle as pickle
35 35 import codeop
36 36 import exceptions
37 37 import glob
38 38 import inspect
39 39 import keyword
40 40 import new
41 41 import os
42 42 import pydoc
43 43 import re
44 44 import shutil
45 45 import string
46 46 import sys
47 47 import tempfile
48 48 import traceback
49 49 import types
50 50 import warnings
51 51 warnings.filterwarnings('ignore', r'.*sets module*')
52 52 from sets import Set
53 53 from pprint import pprint, pformat
54 54
55 55 # IPython's own modules
56 56 #import IPython
57 57 from IPython import Debugger,OInspect,PyColorize,ultraTB
58 58 from IPython.ColorANSI import ColorScheme,ColorSchemeTable # too long names
59 59 from IPython.Extensions import pickleshare
60 60 from IPython.FakeModule import FakeModule
61 61 from IPython.Itpl import Itpl,itpl,printpl,ItplNS,itplns
62 62 from IPython.Logger import Logger
63 63 from IPython.Magic import Magic
64 64 from IPython.Prompts import CachedOutput
65 65 from IPython.ipstruct import Struct
66 66 from IPython.background_jobs import BackgroundJobManager
67 67 from IPython.usage import cmd_line_usage,interactive_usage
68 68 from IPython.genutils import *
69 69 from IPython.strdispatch import StrDispatch
70 70 import IPython.ipapi
71 71 import IPython.history
72 72 import IPython.prefilter as prefilter
73 73 import IPython.shadowns
74 74 # Globals
75 75
76 76 # store the builtin raw_input globally, and use this always, in case user code
77 77 # overwrites it (like wx.py.PyShell does)
78 78 raw_input_original = raw_input
79 79
80 80 # compiled regexps for autoindent management
81 81 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
82 82
83 83
84 84 #****************************************************************************
85 85 # Some utility function definitions
86 86
87 87 ini_spaces_re = re.compile(r'^(\s+)')
88 88
89 89 def num_ini_spaces(strng):
90 90 """Return the number of initial spaces in a string"""
91 91
92 92 ini_spaces = ini_spaces_re.match(strng)
93 93 if ini_spaces:
94 94 return ini_spaces.end()
95 95 else:
96 96 return 0
97 97
98 98 def softspace(file, newvalue):
99 99 """Copied from code.py, to remove the dependency"""
100 100
101 101 oldvalue = 0
102 102 try:
103 103 oldvalue = file.softspace
104 104 except AttributeError:
105 105 pass
106 106 try:
107 107 file.softspace = newvalue
108 108 except (AttributeError, TypeError):
109 109 # "attribute-less object" or "read-only attributes"
110 110 pass
111 111 return oldvalue
112 112
113 113
114 114 #****************************************************************************
115 115 # Local use exceptions
116 116 class SpaceInInput(exceptions.Exception): pass
117 117
118 118
119 119 #****************************************************************************
120 120 # Local use classes
121 121 class Bunch: pass
122 122
123 123 class Undefined: pass
124 124
125 125 class Quitter(object):
126 126 """Simple class to handle exit, similar to Python 2.5's.
127 127
128 128 It handles exiting in an ipython-safe manner, which the one in Python 2.5
129 129 doesn't do (obviously, since it doesn't know about ipython)."""
130 130
131 131 def __init__(self,shell,name):
132 132 self.shell = shell
133 133 self.name = name
134 134
135 135 def __repr__(self):
136 136 return 'Type %s() to exit.' % self.name
137 137 __str__ = __repr__
138 138
139 139 def __call__(self):
140 140 self.shell.exit()
141 141
142 142 class InputList(list):
143 143 """Class to store user input.
144 144
145 145 It's basically a list, but slices return a string instead of a list, thus
146 146 allowing things like (assuming 'In' is an instance):
147 147
148 148 exec In[4:7]
149 149
150 150 or
151 151
152 152 exec In[5:9] + In[14] + In[21:25]"""
153 153
154 154 def __getslice__(self,i,j):
155 155 return ''.join(list.__getslice__(self,i,j))
156 156
157 157 class SyntaxTB(ultraTB.ListTB):
158 158 """Extension which holds some state: the last exception value"""
159 159
160 160 def __init__(self,color_scheme = 'NoColor'):
161 161 ultraTB.ListTB.__init__(self,color_scheme)
162 162 self.last_syntax_error = None
163 163
164 164 def __call__(self, etype, value, elist):
165 165 self.last_syntax_error = value
166 166 ultraTB.ListTB.__call__(self,etype,value,elist)
167 167
168 168 def clear_err_state(self):
169 169 """Return the current error state and clear it"""
170 170 e = self.last_syntax_error
171 171 self.last_syntax_error = None
172 172 return e
173 173
174 174 #****************************************************************************
175 175 # Main IPython class
176 176
177 177 # FIXME: the Magic class is a mixin for now, and will unfortunately remain so
178 178 # until a full rewrite is made. I've cleaned all cross-class uses of
179 179 # attributes and methods, but too much user code out there relies on the
180 180 # equlity %foo == __IP.magic_foo, so I can't actually remove the mixin usage.
181 181 #
182 182 # But at least now, all the pieces have been separated and we could, in
183 183 # principle, stop using the mixin. This will ease the transition to the
184 184 # chainsaw branch.
185 185
186 186 # For reference, the following is the list of 'self.foo' uses in the Magic
187 187 # class as of 2005-12-28. These are names we CAN'T use in the main ipython
188 188 # class, to prevent clashes.
189 189
190 190 # ['self.__class__', 'self.__dict__', 'self._inspect', 'self._ofind',
191 191 # 'self.arg_err', 'self.extract_input', 'self.format_', 'self.lsmagic',
192 192 # 'self.magic_', 'self.options_table', 'self.parse', 'self.shell',
193 193 # 'self.value']
194 194
195 195 class InteractiveShell(object,Magic):
196 196 """An enhanced console for Python."""
197 197
198 198 # class attribute to indicate whether the class supports threads or not.
199 199 # Subclasses with thread support should override this as needed.
200 200 isthreaded = False
201 201
202 202 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
203 203 user_ns=None,user_global_ns=None,banner2='',
204 204 custom_exceptions=((),None),embedded=False):
205 205
206 206 # log system
207 207 self.logger = Logger(self,logfname='ipython_log.py',logmode='rotate')
208 208
209 209 # Job manager (for jobs run as background threads)
210 210 self.jobs = BackgroundJobManager()
211 211
212 212 # Store the actual shell's name
213 213 self.name = name
214 214 self.more = False
215 215
216 216 # We need to know whether the instance is meant for embedding, since
217 217 # global/local namespaces need to be handled differently in that case
218 218 self.embedded = embedded
219 219 if embedded:
220 220 # Control variable so users can, from within the embedded instance,
221 221 # permanently deactivate it.
222 222 self.embedded_active = True
223 223
224 224 # command compiler
225 225 self.compile = codeop.CommandCompiler()
226 226
227 227 # User input buffer
228 228 self.buffer = []
229 229
230 230 # Default name given in compilation of code
231 231 self.filename = '<ipython console>'
232 232
233 233 # Install our own quitter instead of the builtins. For python2.3-2.4,
234 234 # this brings in behavior like 2.5, and for 2.5 it's identical.
235 235 __builtin__.exit = Quitter(self,'exit')
236 236 __builtin__.quit = Quitter(self,'quit')
237 237
238 238 # Make an empty namespace, which extension writers can rely on both
239 239 # existing and NEVER being used by ipython itself. This gives them a
240 240 # convenient location for storing additional information and state
241 241 # their extensions may require, without fear of collisions with other
242 242 # ipython names that may develop later.
243 243 self.meta = Struct()
244 244
245 245 # Create the namespace where the user will operate. user_ns is
246 246 # normally the only one used, and it is passed to the exec calls as
247 247 # the locals argument. But we do carry a user_global_ns namespace
248 248 # given as the exec 'globals' argument, This is useful in embedding
249 249 # situations where the ipython shell opens in a context where the
250 250 # distinction between locals and globals is meaningful. For
251 251 # non-embedded contexts, it is just the same object as the user_ns dict.
252 252
253 253 # FIXME. For some strange reason, __builtins__ is showing up at user
254 254 # level as a dict instead of a module. This is a manual fix, but I
255 255 # should really track down where the problem is coming from. Alex
256 256 # Schmolck reported this problem first.
257 257
258 258 # A useful post by Alex Martelli on this topic:
259 259 # Re: inconsistent value from __builtins__
260 260 # Von: Alex Martelli <aleaxit@yahoo.com>
261 261 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
262 262 # Gruppen: comp.lang.python
263 263
264 264 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
265 265 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
266 266 # > <type 'dict'>
267 267 # > >>> print type(__builtins__)
268 268 # > <type 'module'>
269 269 # > Is this difference in return value intentional?
270 270
271 271 # Well, it's documented that '__builtins__' can be either a dictionary
272 272 # or a module, and it's been that way for a long time. Whether it's
273 273 # intentional (or sensible), I don't know. In any case, the idea is
274 274 # that if you need to access the built-in namespace directly, you
275 275 # should start with "import __builtin__" (note, no 's') which will
276 276 # definitely give you a module. Yeah, it's somewhat confusing:-(.
277 277
278 278 # These routines return properly built dicts as needed by the rest of
279 279 # the code, and can also be used by extension writers to generate
280 280 # properly initialized namespaces.
281 281 user_ns, user_global_ns = IPython.ipapi.make_user_namespaces(user_ns,
282 282 user_global_ns)
283 283
284 284 # Assign namespaces
285 285 # This is the namespace where all normal user variables live
286 286 self.user_ns = user_ns
287 287 self.user_global_ns = user_global_ns
288 288 # A namespace to keep track of internal data structures to prevent
289 289 # them from cluttering user-visible stuff. Will be updated later
290 290 self.internal_ns = {}
291 291
292 292 # Namespace of system aliases. Each entry in the alias
293 293 # table must be a 2-tuple of the form (N,name), where N is the number
294 294 # of positional arguments of the alias.
295 295 self.alias_table = {}
296 296
297 297 # A table holding all the namespaces IPython deals with, so that
298 298 # introspection facilities can search easily.
299 299 self.ns_table = {'user':user_ns,
300 300 'user_global':user_global_ns,
301 301 'alias':self.alias_table,
302 302 'internal':self.internal_ns,
303 303 'builtin':__builtin__.__dict__
304 304 }
305 305 # The user namespace MUST have a pointer to the shell itself.
306 306 self.user_ns[name] = self
307 307
308 308 # We need to insert into sys.modules something that looks like a
309 309 # module but which accesses the IPython namespace, for shelve and
310 310 # pickle to work interactively. Normally they rely on getting
311 311 # everything out of __main__, but for embedding purposes each IPython
312 312 # instance has its own private namespace, so we can't go shoving
313 313 # everything into __main__.
314 314
315 315 # note, however, that we should only do this for non-embedded
316 316 # ipythons, which really mimic the __main__.__dict__ with their own
317 317 # namespace. Embedded instances, on the other hand, should not do
318 318 # this because they need to manage the user local/global namespaces
319 319 # only, but they live within a 'normal' __main__ (meaning, they
320 320 # shouldn't overtake the execution environment of the script they're
321 321 # embedded in).
322 322
323 323 if not embedded:
324 324 try:
325 325 main_name = self.user_ns['__name__']
326 326 except KeyError:
327 327 raise KeyError,'user_ns dictionary MUST have a "__name__" key'
328 328 else:
329 329 #print "pickle hack in place" # dbg
330 330 #print 'main_name:',main_name # dbg
331 331 sys.modules[main_name] = FakeModule(self.user_ns)
332 332
333 333 # Now that FakeModule produces a real module, we've run into a nasty
334 334 # problem: after script execution (via %run), the module where the user
335 335 # code ran is deleted. Now that this object is a true module (needed
336 336 # so docetst and other tools work correctly), the Python module
337 337 # teardown mechanism runs over it, and sets to None every variable
338 # present in that module. This means that later calls to functions
339 # defined in the script (which have become interactively visible after
340 # script exit) fail, because they hold references to objects that have
341 # become overwritten into None. The only solution I see right now is
342 # to protect every FakeModule used by %run by holding an internal
343 # reference to it. This private list will be used for that. The
344 # %reset command will flush it as well.
345 self._user_main_modules = []
346
338 # present in that module. Top-level references to objects from the
339 # script survive, because the user_ns is updated with them. However,
340 # calling functions defined in the script that use other things from
341 # the script will fail, because the function's closure had references
342 # to the original objects, which are now all None. So we must protect
343 # these modules from deletion by keeping a cache. To avoid keeping
344 # stale modules around (we only need the one from the last run), we use
345 # a dict keyed with the full path to the script, so only the last
346 # version of the module is held in the cache. The %reset command will
347 # flush this cache. See the cache_main_mod() and clear_main_mod_cache()
348 # methods for details on use.
349 self._user_main_modules = {}
350
347 351 # List of input with multi-line handling.
348 352 # Fill its zero entry, user counter starts at 1
349 353 self.input_hist = InputList(['\n'])
350 354 # This one will hold the 'raw' input history, without any
351 355 # pre-processing. This will allow users to retrieve the input just as
352 356 # it was exactly typed in by the user, with %hist -r.
353 357 self.input_hist_raw = InputList(['\n'])
354 358
355 359 # list of visited directories
356 360 try:
357 361 self.dir_hist = [os.getcwd()]
358 362 except OSError:
359 363 self.dir_hist = []
360 364
361 365 # dict of output history
362 366 self.output_hist = {}
363 367
364 368 # Get system encoding at startup time. Certain terminals (like Emacs
365 369 # under Win32 have it set to None, and we need to have a known valid
366 370 # encoding to use in the raw_input() method
367 371 try:
368 372 self.stdin_encoding = sys.stdin.encoding or 'ascii'
369 373 except AttributeError:
370 374 self.stdin_encoding = 'ascii'
371 375
372 376 # dict of things NOT to alias (keywords, builtins and some magics)
373 377 no_alias = {}
374 378 no_alias_magics = ['cd','popd','pushd','dhist','alias','unalias']
375 379 for key in keyword.kwlist + no_alias_magics:
376 380 no_alias[key] = 1
377 381 no_alias.update(__builtin__.__dict__)
378 382 self.no_alias = no_alias
379 383
380 384 # make global variables for user access to these
381 385 self.user_ns['_ih'] = self.input_hist
382 386 self.user_ns['_oh'] = self.output_hist
383 387 self.user_ns['_dh'] = self.dir_hist
384 388
385 389 # user aliases to input and output histories
386 390 self.user_ns['In'] = self.input_hist
387 391 self.user_ns['Out'] = self.output_hist
388 392
389 393 self.user_ns['_sh'] = IPython.shadowns
390 394 # Object variable to store code object waiting execution. This is
391 395 # used mainly by the multithreaded shells, but it can come in handy in
392 396 # other situations. No need to use a Queue here, since it's a single
393 397 # item which gets cleared once run.
394 398 self.code_to_run = None
395 399
396 400 # escapes for automatic behavior on the command line
397 401 self.ESC_SHELL = '!'
398 402 self.ESC_SH_CAP = '!!'
399 403 self.ESC_HELP = '?'
400 404 self.ESC_MAGIC = '%'
401 405 self.ESC_QUOTE = ','
402 406 self.ESC_QUOTE2 = ';'
403 407 self.ESC_PAREN = '/'
404 408
405 409 # And their associated handlers
406 410 self.esc_handlers = {self.ESC_PAREN : self.handle_auto,
407 411 self.ESC_QUOTE : self.handle_auto,
408 412 self.ESC_QUOTE2 : self.handle_auto,
409 413 self.ESC_MAGIC : self.handle_magic,
410 414 self.ESC_HELP : self.handle_help,
411 415 self.ESC_SHELL : self.handle_shell_escape,
412 416 self.ESC_SH_CAP : self.handle_shell_escape,
413 417 }
414 418
415 419 # class initializations
416 420 Magic.__init__(self,self)
417 421
418 422 # Python source parser/formatter for syntax highlighting
419 423 pyformat = PyColorize.Parser().format
420 424 self.pycolorize = lambda src: pyformat(src,'str',self.rc['colors'])
421 425
422 426 # hooks holds pointers used for user-side customizations
423 427 self.hooks = Struct()
424 428
425 429 self.strdispatchers = {}
426 430
427 431 # Set all default hooks, defined in the IPython.hooks module.
428 432 hooks = IPython.hooks
429 433 for hook_name in hooks.__all__:
430 434 # default hooks have priority 100, i.e. low; user hooks should have
431 435 # 0-100 priority
432 436 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
433 437 #print "bound hook",hook_name
434 438
435 439 # Flag to mark unconditional exit
436 440 self.exit_now = False
437 441
438 442 self.usage_min = """\
439 443 An enhanced console for Python.
440 444 Some of its features are:
441 445 - Readline support if the readline library is present.
442 446 - Tab completion in the local namespace.
443 447 - Logging of input, see command-line options.
444 448 - System shell escape via ! , eg !ls.
445 449 - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.)
446 450 - Keeps track of locally defined variables via %who, %whos.
447 451 - Show object information with a ? eg ?x or x? (use ?? for more info).
448 452 """
449 453 if usage: self.usage = usage
450 454 else: self.usage = self.usage_min
451 455
452 456 # Storage
453 457 self.rc = rc # This will hold all configuration information
454 458 self.pager = 'less'
455 459 # temporary files used for various purposes. Deleted at exit.
456 460 self.tempfiles = []
457 461
458 462 # Keep track of readline usage (later set by init_readline)
459 463 self.has_readline = False
460 464
461 465 # template for logfile headers. It gets resolved at runtime by the
462 466 # logstart method.
463 467 self.loghead_tpl = \
464 468 """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE ***
465 469 #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW
466 470 #log# opts = %s
467 471 #log# args = %s
468 472 #log# It is safe to make manual edits below here.
469 473 #log#-----------------------------------------------------------------------
470 474 """
471 475 # for pushd/popd management
472 476 try:
473 477 self.home_dir = get_home_dir()
474 478 except HomeDirError,msg:
475 479 fatal(msg)
476 480
477 481 self.dir_stack = []
478 482
479 483 # Functions to call the underlying shell.
480 484
481 485 # The first is similar to os.system, but it doesn't return a value,
482 486 # and it allows interpolation of variables in the user's namespace.
483 487 self.system = lambda cmd: \
484 488 self.hooks.shell_hook(self.var_expand(cmd,depth=2))
485 489
486 490 # These are for getoutput and getoutputerror:
487 491 self.getoutput = lambda cmd: \
488 492 getoutput(self.var_expand(cmd,depth=2),
489 493 header=self.rc.system_header,
490 494 verbose=self.rc.system_verbose)
491 495
492 496 self.getoutputerror = lambda cmd: \
493 497 getoutputerror(self.var_expand(cmd,depth=2),
494 498 header=self.rc.system_header,
495 499 verbose=self.rc.system_verbose)
496 500
497 501
498 502 # keep track of where we started running (mainly for crash post-mortem)
499 503 self.starting_dir = os.getcwd()
500 504
501 505 # Various switches which can be set
502 506 self.CACHELENGTH = 5000 # this is cheap, it's just text
503 507 self.BANNER = "Python %(version)s on %(platform)s\n" % sys.__dict__
504 508 self.banner2 = banner2
505 509
506 510 # TraceBack handlers:
507 511
508 512 # Syntax error handler.
509 513 self.SyntaxTB = SyntaxTB(color_scheme='NoColor')
510 514
511 515 # The interactive one is initialized with an offset, meaning we always
512 516 # want to remove the topmost item in the traceback, which is our own
513 517 # internal code. Valid modes: ['Plain','Context','Verbose']
514 518 self.InteractiveTB = ultraTB.AutoFormattedTB(mode = 'Plain',
515 519 color_scheme='NoColor',
516 520 tb_offset = 1)
517 521
518 522 # IPython itself shouldn't crash. This will produce a detailed
519 523 # post-mortem if it does. But we only install the crash handler for
520 524 # non-threaded shells, the threaded ones use a normal verbose reporter
521 525 # and lose the crash handler. This is because exceptions in the main
522 526 # thread (such as in GUI code) propagate directly to sys.excepthook,
523 527 # and there's no point in printing crash dumps for every user exception.
524 528 if self.isthreaded:
525 529 ipCrashHandler = ultraTB.FormattedTB()
526 530 else:
527 531 from IPython import CrashHandler
528 532 ipCrashHandler = CrashHandler.IPythonCrashHandler(self)
529 533 self.set_crash_handler(ipCrashHandler)
530 534
531 535 # and add any custom exception handlers the user may have specified
532 536 self.set_custom_exc(*custom_exceptions)
533 537
534 538 # indentation management
535 539 self.autoindent = False
536 540 self.indent_current_nsp = 0
537 541
538 542 # Make some aliases automatically
539 543 # Prepare list of shell aliases to auto-define
540 544 if os.name == 'posix':
541 545 auto_alias = ('mkdir mkdir', 'rmdir rmdir',
542 546 'mv mv -i','rm rm -i','cp cp -i',
543 547 'cat cat','less less','clear clear',
544 548 # a better ls
545 549 'ls ls -F',
546 550 # long ls
547 551 'll ls -lF')
548 552 # Extra ls aliases with color, which need special treatment on BSD
549 553 # variants
550 554 ls_extra = ( # color ls
551 555 'lc ls -F -o --color',
552 556 # ls normal files only
553 557 'lf ls -F -o --color %l | grep ^-',
554 558 # ls symbolic links
555 559 'lk ls -F -o --color %l | grep ^l',
556 560 # directories or links to directories,
557 561 'ldir ls -F -o --color %l | grep /$',
558 562 # things which are executable
559 563 'lx ls -F -o --color %l | grep ^-..x',
560 564 )
561 565 # The BSDs don't ship GNU ls, so they don't understand the
562 566 # --color switch out of the box
563 567 if 'bsd' in sys.platform:
564 568 ls_extra = ( # ls normal files only
565 569 'lf ls -lF | grep ^-',
566 570 # ls symbolic links
567 571 'lk ls -lF | grep ^l',
568 572 # directories or links to directories,
569 573 'ldir ls -lF | grep /$',
570 574 # things which are executable
571 575 'lx ls -lF | grep ^-..x',
572 576 )
573 577 auto_alias = auto_alias + ls_extra
574 578 elif os.name in ['nt','dos']:
575 579 auto_alias = ('ls dir /on',
576 580 'ddir dir /ad /on', 'ldir dir /ad /on',
577 581 'mkdir mkdir','rmdir rmdir','echo echo',
578 582 'ren ren','cls cls','copy copy')
579 583 else:
580 584 auto_alias = ()
581 585 self.auto_alias = [s.split(None,1) for s in auto_alias]
582 586
583 587
584 588 # Produce a public API instance
585 589 self.api = IPython.ipapi.IPApi(self)
586 590
587 591 # Call the actual (public) initializer
588 592 self.init_auto_alias()
589 593
590 594 # track which builtins we add, so we can clean up later
591 595 self.builtins_added = {}
592 596 # This method will add the necessary builtins for operation, but
593 597 # tracking what it did via the builtins_added dict.
594 598
595 599 #TODO: remove this, redundant
596 600 self.add_builtins()
597
598
599
600
601 601 # end __init__
602 602
603 603 def var_expand(self,cmd,depth=0):
604 604 """Expand python variables in a string.
605 605
606 606 The depth argument indicates how many frames above the caller should
607 607 be walked to look for the local namespace where to expand variables.
608 608
609 609 The global namespace for expansion is always the user's interactive
610 610 namespace.
611 611 """
612 612
613 613 return str(ItplNS(cmd,
614 614 self.user_ns, # globals
615 615 # Skip our own frame in searching for locals:
616 616 sys._getframe(depth+1).f_locals # locals
617 617 ))
618 618
619 619 def pre_config_initialization(self):
620 620 """Pre-configuration init method
621 621
622 622 This is called before the configuration files are processed to
623 623 prepare the services the config files might need.
624 624
625 625 self.rc already has reasonable default values at this point.
626 626 """
627 627 rc = self.rc
628 628 try:
629 self.db = pickleshare.PickleShareDB(rc.ipythondir + "/db")
629 self.db = pickleshare.PickleShareDB(rc.ipythondir + "/db")
630 630 except exceptions.UnicodeDecodeError:
631 631 print "Your ipythondir can't be decoded to unicode!"
632 632 print "Please set HOME environment variable to something that"
633 633 print r"only has ASCII characters, e.g. c:\home"
634 634 print "Now it is",rc.ipythondir
635 635 sys.exit()
636 self.shadowhist = IPython.history.ShadowHist(self.db)
637
638
636 self.shadowhist = IPython.history.ShadowHist(self.db)
637
639 638 def post_config_initialization(self):
640 639 """Post configuration init method
641 640
642 641 This is called after the configuration files have been processed to
643 642 'finalize' the initialization."""
644 643
645 644 rc = self.rc
646 645
647 646 # Object inspector
648 647 self.inspector = OInspect.Inspector(OInspect.InspectColors,
649 648 PyColorize.ANSICodeColors,
650 649 'NoColor',
651 650 rc.object_info_string_level)
652 651
653 652 self.rl_next_input = None
654 653 self.rl_do_indent = False
655 654 # Load readline proper
656 655 if rc.readline:
657 656 self.init_readline()
658 657
659 658
660 659 # local shortcut, this is used a LOT
661 660 self.log = self.logger.log
662 661
663 662 # Initialize cache, set in/out prompts and printing system
664 663 self.outputcache = CachedOutput(self,
665 664 rc.cache_size,
666 665 rc.pprint,
667 666 input_sep = rc.separate_in,
668 667 output_sep = rc.separate_out,
669 668 output_sep2 = rc.separate_out2,
670 669 ps1 = rc.prompt_in1,
671 670 ps2 = rc.prompt_in2,
672 671 ps_out = rc.prompt_out,
673 672 pad_left = rc.prompts_pad_left)
674 673
675 674 # user may have over-ridden the default print hook:
676 675 try:
677 676 self.outputcache.__class__.display = self.hooks.display
678 677 except AttributeError:
679 678 pass
680 679
681 680 # I don't like assigning globally to sys, because it means when
682 681 # embedding instances, each embedded instance overrides the previous
683 682 # choice. But sys.displayhook seems to be called internally by exec,
684 683 # so I don't see a way around it. We first save the original and then
685 684 # overwrite it.
686 685 self.sys_displayhook = sys.displayhook
687 686 sys.displayhook = self.outputcache
688 687
689 688 # Do a proper resetting of doctest, including the necessary displayhook
690 689 # monkeypatching
691 690 try:
692 691 doctest_reload()
693 692 except ImportError:
694 693 warn("doctest module does not exist.")
695 694
696 695 # Set user colors (don't do it in the constructor above so that it
697 696 # doesn't crash if colors option is invalid)
698 697 self.magic_colors(rc.colors)
699 698
700 699 # Set calling of pdb on exceptions
701 700 self.call_pdb = rc.pdb
702 701
703 702 # Load user aliases
704 703 for alias in rc.alias:
705 704 self.magic_alias(alias)
706 705
707 706 self.hooks.late_startup_hook()
708 707
709 708 for cmd in self.rc.autoexec:
710 709 #print "autoexec>",cmd #dbg
711 710 self.api.runlines(cmd)
712 711
713 712 batchrun = False
714 713 for batchfile in [path(arg) for arg in self.rc.args
715 714 if arg.lower().endswith('.ipy')]:
716 715 if not batchfile.isfile():
717 716 print "No such batch file:", batchfile
718 717 continue
719 718 self.api.runlines(batchfile.text())
720 719 batchrun = True
721 720 # without -i option, exit after running the batch file
722 721 if batchrun and not self.rc.interact:
723 722 self.ask_exit()
724 723
725 724 def add_builtins(self):
726 725 """Store ipython references into the builtin namespace.
727 726
728 727 Some parts of ipython operate via builtins injected here, which hold a
729 728 reference to IPython itself."""
730 729
731 730 # TODO: deprecate all of these, they are unsafe
732 731 builtins_new = dict(__IPYTHON__ = self,
733 732 ip_set_hook = self.set_hook,
734 733 jobs = self.jobs,
735 734 ipmagic = wrap_deprecated(self.ipmagic,'_ip.magic()'),
736 735 ipalias = wrap_deprecated(self.ipalias),
737 736 ipsystem = wrap_deprecated(self.ipsystem,'_ip.system()'),
738 737 #_ip = self.api
739 738 )
740 739 for biname,bival in builtins_new.items():
741 740 try:
742 741 # store the orignal value so we can restore it
743 742 self.builtins_added[biname] = __builtin__.__dict__[biname]
744 743 except KeyError:
745 744 # or mark that it wasn't defined, and we'll just delete it at
746 745 # cleanup
747 746 self.builtins_added[biname] = Undefined
748 747 __builtin__.__dict__[biname] = bival
749 748
750 749 # Keep in the builtins a flag for when IPython is active. We set it
751 750 # with setdefault so that multiple nested IPythons don't clobber one
752 751 # another. Each will increase its value by one upon being activated,
753 752 # which also gives us a way to determine the nesting level.
754 753 __builtin__.__dict__.setdefault('__IPYTHON__active',0)
755 754
756 755 def clean_builtins(self):
757 756 """Remove any builtins which might have been added by add_builtins, or
758 757 restore overwritten ones to their previous values."""
759 758 for biname,bival in self.builtins_added.items():
760 759 if bival is Undefined:
761 760 del __builtin__.__dict__[biname]
762 761 else:
763 762 __builtin__.__dict__[biname] = bival
764 763 self.builtins_added.clear()
765 764
766 765 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
767 766 """set_hook(name,hook) -> sets an internal IPython hook.
768 767
769 768 IPython exposes some of its internal API as user-modifiable hooks. By
770 769 adding your function to one of these hooks, you can modify IPython's
771 770 behavior to call at runtime your own routines."""
772 771
773 772 # At some point in the future, this should validate the hook before it
774 773 # accepts it. Probably at least check that the hook takes the number
775 774 # of args it's supposed to.
776 775
777 776 f = new.instancemethod(hook,self,self.__class__)
778 777
779 778 # check if the hook is for strdispatcher first
780 779 if str_key is not None:
781 780 sdp = self.strdispatchers.get(name, StrDispatch())
782 781 sdp.add_s(str_key, f, priority )
783 782 self.strdispatchers[name] = sdp
784 783 return
785 784 if re_key is not None:
786 785 sdp = self.strdispatchers.get(name, StrDispatch())
787 786 sdp.add_re(re.compile(re_key), f, priority )
788 787 self.strdispatchers[name] = sdp
789 788 return
790 789
791 790 dp = getattr(self.hooks, name, None)
792 791 if name not in IPython.hooks.__all__:
793 792 print "Warning! Hook '%s' is not one of %s" % (name, IPython.hooks.__all__ )
794 793 if not dp:
795 794 dp = IPython.hooks.CommandChainDispatcher()
796 795
797 796 try:
798 797 dp.add(f,priority)
799 798 except AttributeError:
800 799 # it was not commandchain, plain old func - replace
801 800 dp = f
802 801
803 802 setattr(self.hooks,name, dp)
804 803
805 804
806 805 #setattr(self.hooks,name,new.instancemethod(hook,self,self.__class__))
807 806
808 807 def set_crash_handler(self,crashHandler):
809 808 """Set the IPython crash handler.
810 809
811 810 This must be a callable with a signature suitable for use as
812 811 sys.excepthook."""
813 812
814 813 # Install the given crash handler as the Python exception hook
815 814 sys.excepthook = crashHandler
816 815
817 816 # The instance will store a pointer to this, so that runtime code
818 817 # (such as magics) can access it. This is because during the
819 818 # read-eval loop, it gets temporarily overwritten (to deal with GUI
820 819 # frameworks).
821 820 self.sys_excepthook = sys.excepthook
822 821
823 822
824 823 def set_custom_exc(self,exc_tuple,handler):
825 824 """set_custom_exc(exc_tuple,handler)
826 825
827 826 Set a custom exception handler, which will be called if any of the
828 827 exceptions in exc_tuple occur in the mainloop (specifically, in the
829 828 runcode() method.
830 829
831 830 Inputs:
832 831
833 832 - exc_tuple: a *tuple* of valid exceptions to call the defined
834 833 handler for. It is very important that you use a tuple, and NOT A
835 834 LIST here, because of the way Python's except statement works. If
836 835 you only want to trap a single exception, use a singleton tuple:
837 836
838 837 exc_tuple == (MyCustomException,)
839 838
840 839 - handler: this must be defined as a function with the following
841 840 basic interface: def my_handler(self,etype,value,tb).
842 841
843 842 This will be made into an instance method (via new.instancemethod)
844 843 of IPython itself, and it will be called if any of the exceptions
845 844 listed in the exc_tuple are caught. If the handler is None, an
846 845 internal basic one is used, which just prints basic info.
847 846
848 847 WARNING: by putting in your own exception handler into IPython's main
849 848 execution loop, you run a very good chance of nasty crashes. This
850 849 facility should only be used if you really know what you are doing."""
851 850
852 851 assert type(exc_tuple)==type(()) , \
853 852 "The custom exceptions must be given AS A TUPLE."
854 853
855 854 def dummy_handler(self,etype,value,tb):
856 855 print '*** Simple custom exception handler ***'
857 856 print 'Exception type :',etype
858 857 print 'Exception value:',value
859 858 print 'Traceback :',tb
860 859 print 'Source code :','\n'.join(self.buffer)
861 860
862 861 if handler is None: handler = dummy_handler
863 862
864 863 self.CustomTB = new.instancemethod(handler,self,self.__class__)
865 864 self.custom_exceptions = exc_tuple
866 865
867 866 def set_custom_completer(self,completer,pos=0):
868 867 """set_custom_completer(completer,pos=0)
869 868
870 869 Adds a new custom completer function.
871 870
872 871 The position argument (defaults to 0) is the index in the completers
873 872 list where you want the completer to be inserted."""
874 873
875 874 newcomp = new.instancemethod(completer,self.Completer,
876 875 self.Completer.__class__)
877 876 self.Completer.matchers.insert(pos,newcomp)
878 877
879 878 def set_completer(self):
880 879 """reset readline's completer to be our own."""
881 880 self.readline.set_completer(self.Completer.complete)
882 881
883 882 def _get_call_pdb(self):
884 883 return self._call_pdb
885 884
886 885 def _set_call_pdb(self,val):
887 886
888 887 if val not in (0,1,False,True):
889 888 raise ValueError,'new call_pdb value must be boolean'
890 889
891 890 # store value in instance
892 891 self._call_pdb = val
893 892
894 893 # notify the actual exception handlers
895 894 self.InteractiveTB.call_pdb = val
896 895 if self.isthreaded:
897 896 try:
898 897 self.sys_excepthook.call_pdb = val
899 898 except:
900 899 warn('Failed to activate pdb for threaded exception handler')
901 900
902 901 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
903 902 'Control auto-activation of pdb at exceptions')
904 903
905
906 904 # These special functions get installed in the builtin namespace, to
907 905 # provide programmatic (pure python) access to magics, aliases and system
908 906 # calls. This is important for logging, user scripting, and more.
909 907
910 908 # We are basically exposing, via normal python functions, the three
911 909 # mechanisms in which ipython offers special call modes (magics for
912 910 # internal control, aliases for direct system access via pre-selected
913 911 # names, and !cmd for calling arbitrary system commands).
914 912
915 913 def ipmagic(self,arg_s):
916 914 """Call a magic function by name.
917 915
918 916 Input: a string containing the name of the magic function to call and any
919 917 additional arguments to be passed to the magic.
920 918
921 919 ipmagic('name -opt foo bar') is equivalent to typing at the ipython
922 920 prompt:
923 921
924 922 In[1]: %name -opt foo bar
925 923
926 924 To call a magic without arguments, simply use ipmagic('name').
927 925
928 926 This provides a proper Python function to call IPython's magics in any
929 927 valid Python code you can type at the interpreter, including loops and
930 928 compound statements. It is added by IPython to the Python builtin
931 929 namespace upon initialization."""
932 930
933 931 args = arg_s.split(' ',1)
934 932 magic_name = args[0]
935 933 magic_name = magic_name.lstrip(self.ESC_MAGIC)
936 934
937 935 try:
938 936 magic_args = args[1]
939 937 except IndexError:
940 938 magic_args = ''
941 939 fn = getattr(self,'magic_'+magic_name,None)
942 940 if fn is None:
943 941 error("Magic function `%s` not found." % magic_name)
944 942 else:
945 943 magic_args = self.var_expand(magic_args,1)
946 944 return fn(magic_args)
947 945
948 946 def ipalias(self,arg_s):
949 947 """Call an alias by name.
950 948
951 949 Input: a string containing the name of the alias to call and any
952 950 additional arguments to be passed to the magic.
953 951
954 952 ipalias('name -opt foo bar') is equivalent to typing at the ipython
955 953 prompt:
956 954
957 955 In[1]: name -opt foo bar
958 956
959 957 To call an alias without arguments, simply use ipalias('name').
960 958
961 959 This provides a proper Python function to call IPython's aliases in any
962 960 valid Python code you can type at the interpreter, including loops and
963 961 compound statements. It is added by IPython to the Python builtin
964 962 namespace upon initialization."""
965 963
966 964 args = arg_s.split(' ',1)
967 965 alias_name = args[0]
968 966 try:
969 967 alias_args = args[1]
970 968 except IndexError:
971 969 alias_args = ''
972 970 if alias_name in self.alias_table:
973 971 self.call_alias(alias_name,alias_args)
974 972 else:
975 973 error("Alias `%s` not found." % alias_name)
976 974
977 975 def ipsystem(self,arg_s):
978 976 """Make a system call, using IPython."""
979 977
980 978 self.system(arg_s)
981 979
982 980 def complete(self,text):
983 981 """Return a sorted list of all possible completions on text.
984 982
985 983 Inputs:
986 984
987 985 - text: a string of text to be completed on.
988 986
989 987 This is a wrapper around the completion mechanism, similar to what
990 988 readline does at the command line when the TAB key is hit. By
991 989 exposing it as a method, it can be used by other non-readline
992 990 environments (such as GUIs) for text completion.
993 991
994 992 Simple usage example:
995 993
996 994 In [7]: x = 'hello'
997 995
998 996 In [8]: x
999 997 Out[8]: 'hello'
1000 998
1001 999 In [9]: print x
1002 1000 hello
1003 1001
1004 1002 In [10]: _ip.IP.complete('x.l')
1005 1003 Out[10]: ['x.ljust', 'x.lower', 'x.lstrip']
1006 1004 """
1007 1005
1008 1006 complete = self.Completer.complete
1009 1007 state = 0
1010 1008 # use a dict so we get unique keys, since ipyhton's multiple
1011 1009 # completers can return duplicates. When we make 2.4 a requirement,
1012 1010 # start using sets instead, which are faster.
1013 1011 comps = {}
1014 1012 while True:
1015 1013 newcomp = complete(text,state,line_buffer=text)
1016 1014 if newcomp is None:
1017 1015 break
1018 1016 comps[newcomp] = 1
1019 1017 state += 1
1020 1018 outcomps = comps.keys()
1021 1019 outcomps.sort()
1022 1020 #print "T:",text,"OC:",outcomps # dbg
1023 1021 #print "vars:",self.user_ns.keys()
1024 1022 return outcomps
1025 1023
1026 1024 def set_completer_frame(self, frame=None):
1027 1025 if frame:
1028 1026 self.Completer.namespace = frame.f_locals
1029 1027 self.Completer.global_namespace = frame.f_globals
1030 1028 else:
1031 1029 self.Completer.namespace = self.user_ns
1032 1030 self.Completer.global_namespace = self.user_global_ns
1033 1031
1034 1032 def init_auto_alias(self):
1035 1033 """Define some aliases automatically.
1036 1034
1037 1035 These are ALL parameter-less aliases"""
1038 1036
1039 1037 for alias,cmd in self.auto_alias:
1040 1038 self.getapi().defalias(alias,cmd)
1041 1039
1042 1040
1043 1041 def alias_table_validate(self,verbose=0):
1044 1042 """Update information about the alias table.
1045 1043
1046 1044 In particular, make sure no Python keywords/builtins are in it."""
1047 1045
1048 1046 no_alias = self.no_alias
1049 1047 for k in self.alias_table.keys():
1050 1048 if k in no_alias:
1051 1049 del self.alias_table[k]
1052 1050 if verbose:
1053 1051 print ("Deleting alias <%s>, it's a Python "
1054 1052 "keyword or builtin." % k)
1055 1053
1056 1054 def set_autoindent(self,value=None):
1057 1055 """Set the autoindent flag, checking for readline support.
1058 1056
1059 1057 If called with no arguments, it acts as a toggle."""
1060 1058
1061 1059 if not self.has_readline:
1062 1060 if os.name == 'posix':
1063 1061 warn("The auto-indent feature requires the readline library")
1064 1062 self.autoindent = 0
1065 1063 return
1066 1064 if value is None:
1067 1065 self.autoindent = not self.autoindent
1068 1066 else:
1069 1067 self.autoindent = value
1070 1068
1071 1069 def rc_set_toggle(self,rc_field,value=None):
1072 1070 """Set or toggle a field in IPython's rc config. structure.
1073 1071
1074 1072 If called with no arguments, it acts as a toggle.
1075 1073
1076 1074 If called with a non-existent field, the resulting AttributeError
1077 1075 exception will propagate out."""
1078 1076
1079 1077 rc_val = getattr(self.rc,rc_field)
1080 1078 if value is None:
1081 1079 value = not rc_val
1082 1080 setattr(self.rc,rc_field,value)
1083 1081
1084 1082 def user_setup(self,ipythondir,rc_suffix,mode='install'):
1085 1083 """Install the user configuration directory.
1086 1084
1087 1085 Can be called when running for the first time or to upgrade the user's
1088 1086 .ipython/ directory with the mode parameter. Valid modes are 'install'
1089 1087 and 'upgrade'."""
1090 1088
1091 1089 def wait():
1092 1090 try:
1093 1091 raw_input("Please press <RETURN> to start IPython.")
1094 1092 except EOFError:
1095 1093 print >> Term.cout
1096 1094 print '*'*70
1097 1095
1098 1096 cwd = os.getcwd() # remember where we started
1099 1097 glb = glob.glob
1100 1098 print '*'*70
1101 1099 if mode == 'install':
1102 1100 print \
1103 1101 """Welcome to IPython. I will try to create a personal configuration directory
1104 1102 where you can customize many aspects of IPython's functionality in:\n"""
1105 1103 else:
1106 1104 print 'I am going to upgrade your configuration in:'
1107 1105
1108 1106 print ipythondir
1109 1107
1110 1108 rcdirend = os.path.join('IPython','UserConfig')
1111 1109 cfg = lambda d: os.path.join(d,rcdirend)
1112 1110 try:
1113 1111 rcdir = filter(os.path.isdir,map(cfg,sys.path))[0]
1114 1112 print "Initializing from configuration",rcdir
1115 1113 except IndexError:
1116 1114 warning = """
1117 1115 Installation error. IPython's directory was not found.
1118 1116
1119 1117 Check the following:
1120 1118
1121 1119 The ipython/IPython directory should be in a directory belonging to your
1122 1120 PYTHONPATH environment variable (that is, it should be in a directory
1123 1121 belonging to sys.path). You can copy it explicitly there or just link to it.
1124 1122
1125 1123 IPython will create a minimal default configuration for you.
1126 1124
1127 1125 """
1128 1126 warn(warning)
1129 1127 wait()
1130 1128
1131 1129 if sys.platform =='win32':
1132 1130 inif = 'ipythonrc.ini'
1133 1131 else:
1134 1132 inif = 'ipythonrc'
1135 minimal_setup = {'ipy_user_conf.py' : 'import ipy_defaults', inif : '# intentionally left blank' }
1133 minimal_setup = {'ipy_user_conf.py' : 'import ipy_defaults',
1134 inif : '# intentionally left blank' }
1136 1135 os.makedirs(ipythondir, mode = 0777)
1137 1136 for f, cont in minimal_setup.items():
1138 1137 open(ipythondir + '/' + f,'w').write(cont)
1139 1138
1140 1139 return
1141 1140
1142 1141 if mode == 'install':
1143 1142 try:
1144 1143 shutil.copytree(rcdir,ipythondir)
1145 1144 os.chdir(ipythondir)
1146 1145 rc_files = glb("ipythonrc*")
1147 1146 for rc_file in rc_files:
1148 1147 os.rename(rc_file,rc_file+rc_suffix)
1149 1148 except:
1150 1149 warning = """
1151 1150
1152 1151 There was a problem with the installation:
1153 1152 %s
1154 1153 Try to correct it or contact the developers if you think it's a bug.
1155 1154 IPython will proceed with builtin defaults.""" % sys.exc_info()[1]
1156 1155 warn(warning)
1157 1156 wait()
1158 1157 return
1159 1158
1160 1159 elif mode == 'upgrade':
1161 1160 try:
1162 1161 os.chdir(ipythondir)
1163 1162 except:
1164 1163 print """
1165 1164 Can not upgrade: changing to directory %s failed. Details:
1166 1165 %s
1167 1166 """ % (ipythondir,sys.exc_info()[1])
1168 1167 wait()
1169 1168 return
1170 1169 else:
1171 1170 sources = glb(os.path.join(rcdir,'[A-Za-z]*'))
1172 1171 for new_full_path in sources:
1173 1172 new_filename = os.path.basename(new_full_path)
1174 1173 if new_filename.startswith('ipythonrc'):
1175 1174 new_filename = new_filename + rc_suffix
1176 1175 # The config directory should only contain files, skip any
1177 1176 # directories which may be there (like CVS)
1178 1177 if os.path.isdir(new_full_path):
1179 1178 continue
1180 1179 if os.path.exists(new_filename):
1181 1180 old_file = new_filename+'.old'
1182 1181 if os.path.exists(old_file):
1183 1182 os.remove(old_file)
1184 1183 os.rename(new_filename,old_file)
1185 1184 shutil.copy(new_full_path,new_filename)
1186 1185 else:
1187 1186 raise ValueError,'unrecognized mode for install:',`mode`
1188 1187
1189 1188 # Fix line-endings to those native to each platform in the config
1190 1189 # directory.
1191 1190 try:
1192 1191 os.chdir(ipythondir)
1193 1192 except:
1194 1193 print """
1195 1194 Problem: changing to directory %s failed.
1196 1195 Details:
1197 1196 %s
1198 1197
1199 1198 Some configuration files may have incorrect line endings. This should not
1200 1199 cause any problems during execution. """ % (ipythondir,sys.exc_info()[1])
1201 1200 wait()
1202 1201 else:
1203 1202 for fname in glb('ipythonrc*'):
1204 1203 try:
1205 1204 native_line_ends(fname,backup=0)
1206 1205 except IOError:
1207 1206 pass
1208 1207
1209 1208 if mode == 'install':
1210 1209 print """
1211 1210 Successful installation!
1212 1211
1213 1212 Please read the sections 'Initial Configuration' and 'Quick Tips' in the
1214 1213 IPython manual (there are both HTML and PDF versions supplied with the
1215 1214 distribution) to make sure that your system environment is properly configured
1216 1215 to take advantage of IPython's features.
1217 1216
1218 1217 Important note: the configuration system has changed! The old system is
1219 1218 still in place, but its setting may be partly overridden by the settings in
1220 1219 "~/.ipython/ipy_user_conf.py" config file. Please take a look at the file
1221 1220 if some of the new settings bother you.
1222 1221
1223 1222 """
1224 1223 else:
1225 1224 print """
1226 1225 Successful upgrade!
1227 1226
1228 1227 All files in your directory:
1229 1228 %(ipythondir)s
1230 1229 which would have been overwritten by the upgrade were backed up with a .old
1231 1230 extension. If you had made particular customizations in those files you may
1232 1231 want to merge them back into the new files.""" % locals()
1233 1232 wait()
1234 1233 os.chdir(cwd)
1235 1234 # end user_setup()
1236 1235
1237 1236 def atexit_operations(self):
1238 1237 """This will be executed at the time of exit.
1239 1238
1240 1239 Saving of persistent data should be performed here. """
1241 1240
1242 1241 #print '*** IPython exit cleanup ***' # dbg
1243 1242 # input history
1244 1243 self.savehist()
1245 1244
1246 1245 # Cleanup all tempfiles left around
1247 1246 for tfile in self.tempfiles:
1248 1247 try:
1249 1248 os.unlink(tfile)
1250 1249 except OSError:
1251 1250 pass
1252 1251
1253 1252 self.hooks.shutdown_hook()
1254 1253
1255 1254 def savehist(self):
1256 1255 """Save input history to a file (via readline library)."""
1257 1256
1258 1257 if not self.has_readline:
1259 1258 return
1260 1259
1261 1260 try:
1262 1261 self.readline.write_history_file(self.histfile)
1263 1262 except:
1264 1263 print 'Unable to save IPython command history to file: ' + \
1265 1264 `self.histfile`
1266 1265
1267 1266 def reloadhist(self):
1268 1267 """Reload the input history from disk file."""
1269 1268
1270 1269 if self.has_readline:
1271 1270 try:
1272 1271 self.readline.clear_history()
1273 1272 self.readline.read_history_file(self.shell.histfile)
1274 1273 except AttributeError:
1275 1274 pass
1276 1275
1277 1276
1278 1277 def history_saving_wrapper(self, func):
1279 1278 """ Wrap func for readline history saving
1280 1279
1281 1280 Convert func into callable that saves & restores
1282 1281 history around the call """
1283 1282
1284 1283 if not self.has_readline:
1285 1284 return func
1286 1285
1287 1286 def wrapper():
1288 1287 self.savehist()
1289 1288 try:
1290 1289 func()
1291 1290 finally:
1292 1291 readline.read_history_file(self.histfile)
1293 1292 return wrapper
1294
1295 1293
1296 1294 def pre_readline(self):
1297 1295 """readline hook to be used at the start of each line.
1298 1296
1299 1297 Currently it handles auto-indent only."""
1300 1298
1301 1299 #debugx('self.indent_current_nsp','pre_readline:')
1302 1300
1303 1301 if self.rl_do_indent:
1304 1302 self.readline.insert_text(self.indent_current_str())
1305 1303 if self.rl_next_input is not None:
1306 1304 self.readline.insert_text(self.rl_next_input)
1307 1305 self.rl_next_input = None
1308 1306
1309 1307 def init_readline(self):
1310 1308 """Command history completion/saving/reloading."""
1311 1309
1312 1310
1313 1311 import IPython.rlineimpl as readline
1314 1312
1315 1313 if not readline.have_readline:
1316 1314 self.has_readline = 0
1317 1315 self.readline = None
1318 1316 # no point in bugging windows users with this every time:
1319 1317 warn('Readline services not available on this platform.')
1320 1318 else:
1321 1319 sys.modules['readline'] = readline
1322 1320 import atexit
1323 1321 from IPython.completer import IPCompleter
1324 1322 self.Completer = IPCompleter(self,
1325 1323 self.user_ns,
1326 1324 self.user_global_ns,
1327 1325 self.rc.readline_omit__names,
1328 1326 self.alias_table)
1329 1327 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1330 1328 self.strdispatchers['complete_command'] = sdisp
1331 1329 self.Completer.custom_completers = sdisp
1332 1330 # Platform-specific configuration
1333 1331 if os.name == 'nt':
1334 1332 self.readline_startup_hook = readline.set_pre_input_hook
1335 1333 else:
1336 1334 self.readline_startup_hook = readline.set_startup_hook
1337 1335
1338 1336 # Load user's initrc file (readline config)
1339 1337 # Or if libedit is used, load editrc.
1340 1338 inputrc_name = os.environ.get('INPUTRC')
1341 1339 if inputrc_name is None:
1342 1340 home_dir = get_home_dir()
1343 1341 if home_dir is not None:
1344 1342 inputrc_name = '.inputrc'
1345 1343 if readline.uses_libedit:
1346 1344 inputrc_name = '.editrc'
1347 1345 inputrc_name = os.path.join(home_dir, inputrc_name)
1348 1346 if os.path.isfile(inputrc_name):
1349 1347 try:
1350 1348 readline.read_init_file(inputrc_name)
1351 1349 except:
1352 1350 warn('Problems reading readline initialization file <%s>'
1353 1351 % inputrc_name)
1354 1352
1355 1353 self.has_readline = 1
1356 1354 self.readline = readline
1357 1355 # save this in sys so embedded copies can restore it properly
1358 1356 sys.ipcompleter = self.Completer.complete
1359 1357 self.set_completer()
1360 1358
1361 1359 # Configure readline according to user's prefs
1362 1360 # This is only done if GNU readline is being used. If libedit
1363 1361 # is being used (as on Leopard) the readline config is
1364 1362 # not run as the syntax for libedit is different.
1365 1363 if not readline.uses_libedit:
1366 1364 for rlcommand in self.rc.readline_parse_and_bind:
1367 1365 readline.parse_and_bind(rlcommand)
1368 1366
1369 1367 # remove some chars from the delimiters list
1370 1368 delims = readline.get_completer_delims()
1371 1369 delims = delims.translate(string._idmap,
1372 1370 self.rc.readline_remove_delims)
1373 1371 readline.set_completer_delims(delims)
1374 1372 # otherwise we end up with a monster history after a while:
1375 1373 readline.set_history_length(1000)
1376 1374 try:
1377 1375 #print '*** Reading readline history' # dbg
1378 1376 readline.read_history_file(self.histfile)
1379 1377 except IOError:
1380 1378 pass # It doesn't exist yet.
1381 1379
1382 1380 atexit.register(self.atexit_operations)
1383 1381 del atexit
1384 1382
1385 1383 # Configure auto-indent for all platforms
1386 1384 self.set_autoindent(self.rc.autoindent)
1387 1385
1388 1386 def ask_yes_no(self,prompt,default=True):
1389 1387 if self.rc.quiet:
1390 1388 return True
1391 1389 return ask_yes_no(prompt,default)
1392
1390
1391 def cache_main_mod(self,mod):
1392 """Cache a main module.
1393
1394 When scripts are executed via %run, we must keep a reference to their
1395 __main__ module (a FakeModule instance) around so that Python doesn't
1396 clear it, rendering objects defined therein useless.
1397
1398 This method keeps said reference in a private dict, keyed by the
1399 absolute path of the module object (which corresponds to the script
1400 path). This way, for multiple executions of the same script we only
1401 keep one copy of __main__ (the last one), thus preventing memory leaks
1402 from old references while allowing the objects from the last execution
1403 to be accessible.
1404
1405 Parameters
1406 ----------
1407 mod : a module object
1408
1409 Examples
1410 --------
1411
1412 In [10]: import IPython
1413
1414 In [11]: _ip.IP.cache_main_mod(IPython)
1415
1416 In [12]: IPython.__file__ in _ip.IP._user_main_modules
1417 Out[12]: True
1418 """
1419 self._user_main_modules[os.path.abspath(mod.__file__) ] = mod
1420
1421 def clear_main_mod_cache(self):
1422 """Clear the cache of main modules.
1423
1424 Mainly for use by utilities like %reset.
1425
1426 Examples
1427 --------
1428
1429 In [15]: import IPython
1430
1431 In [16]: _ip.IP.cache_main_mod(IPython)
1432
1433 In [17]: len(_ip.IP._user_main_modules) > 0
1434 Out[17]: True
1435
1436 In [18]: _ip.IP.clear_main_mod_cache()
1437
1438 In [19]: len(_ip.IP._user_main_modules) == 0
1439 Out[19]: True
1440 """
1441 self._user_main_modules.clear()
1442
1393 1443 def _should_recompile(self,e):
1394 1444 """Utility routine for edit_syntax_error"""
1395 1445
1396 1446 if e.filename in ('<ipython console>','<input>','<string>',
1397 1447 '<console>','<BackgroundJob compilation>',
1398 1448 None):
1399 1449
1400 1450 return False
1401 1451 try:
1402 1452 if (self.rc.autoedit_syntax and
1403 1453 not self.ask_yes_no('Return to editor to correct syntax error? '
1404 1454 '[Y/n] ','y')):
1405 1455 return False
1406 1456 except EOFError:
1407 1457 return False
1408 1458
1409 1459 def int0(x):
1410 1460 try:
1411 1461 return int(x)
1412 1462 except TypeError:
1413 1463 return 0
1414 1464 # always pass integer line and offset values to editor hook
1415 1465 self.hooks.fix_error_editor(e.filename,
1416 1466 int0(e.lineno),int0(e.offset),e.msg)
1417 1467 return True
1418 1468
1419 1469 def edit_syntax_error(self):
1420 1470 """The bottom half of the syntax error handler called in the main loop.
1421 1471
1422 1472 Loop until syntax error is fixed or user cancels.
1423 1473 """
1424 1474
1425 1475 while self.SyntaxTB.last_syntax_error:
1426 1476 # copy and clear last_syntax_error
1427 1477 err = self.SyntaxTB.clear_err_state()
1428 1478 if not self._should_recompile(err):
1429 1479 return
1430 1480 try:
1431 1481 # may set last_syntax_error again if a SyntaxError is raised
1432 1482 self.safe_execfile(err.filename,self.user_ns)
1433 1483 except:
1434 1484 self.showtraceback()
1435 1485 else:
1436 1486 try:
1437 1487 f = file(err.filename)
1438 1488 try:
1439 1489 sys.displayhook(f.read())
1440 1490 finally:
1441 1491 f.close()
1442 1492 except:
1443 1493 self.showtraceback()
1444 1494
1445 1495 def showsyntaxerror(self, filename=None):
1446 1496 """Display the syntax error that just occurred.
1447 1497
1448 1498 This doesn't display a stack trace because there isn't one.
1449 1499
1450 1500 If a filename is given, it is stuffed in the exception instead
1451 1501 of what was there before (because Python's parser always uses
1452 1502 "<string>" when reading from a string).
1453 1503 """
1454 1504 etype, value, last_traceback = sys.exc_info()
1455 1505
1456 1506 # See note about these variables in showtraceback() below
1457 1507 sys.last_type = etype
1458 1508 sys.last_value = value
1459 1509 sys.last_traceback = last_traceback
1460 1510
1461 1511 if filename and etype is SyntaxError:
1462 1512 # Work hard to stuff the correct filename in the exception
1463 1513 try:
1464 1514 msg, (dummy_filename, lineno, offset, line) = value
1465 1515 except:
1466 1516 # Not the format we expect; leave it alone
1467 1517 pass
1468 1518 else:
1469 1519 # Stuff in the right filename
1470 1520 try:
1471 1521 # Assume SyntaxError is a class exception
1472 1522 value = SyntaxError(msg, (filename, lineno, offset, line))
1473 1523 except:
1474 1524 # If that failed, assume SyntaxError is a string
1475 1525 value = msg, (filename, lineno, offset, line)
1476 1526 self.SyntaxTB(etype,value,[])
1477 1527
1478 1528 def debugger(self,force=False):
1479 1529 """Call the pydb/pdb debugger.
1480 1530
1481 1531 Keywords:
1482 1532
1483 1533 - force(False): by default, this routine checks the instance call_pdb
1484 1534 flag and does not actually invoke the debugger if the flag is false.
1485 1535 The 'force' option forces the debugger to activate even if the flag
1486 1536 is false.
1487 1537 """
1488 1538
1489 1539 if not (force or self.call_pdb):
1490 1540 return
1491 1541
1492 1542 if not hasattr(sys,'last_traceback'):
1493 1543 error('No traceback has been produced, nothing to debug.')
1494 1544 return
1495 1545
1496 1546 # use pydb if available
1497 1547 if Debugger.has_pydb:
1498 1548 from pydb import pm
1499 1549 else:
1500 1550 # fallback to our internal debugger
1501 1551 pm = lambda : self.InteractiveTB.debugger(force=True)
1502 1552 self.history_saving_wrapper(pm)()
1503 1553
1504 1554 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None):
1505 1555 """Display the exception that just occurred.
1506 1556
1507 1557 If nothing is known about the exception, this is the method which
1508 1558 should be used throughout the code for presenting user tracebacks,
1509 1559 rather than directly invoking the InteractiveTB object.
1510 1560
1511 1561 A specific showsyntaxerror() also exists, but this method can take
1512 1562 care of calling it if needed, so unless you are explicitly catching a
1513 1563 SyntaxError exception, don't try to analyze the stack manually and
1514 1564 simply call this method."""
1515 1565
1516 1566
1517 1567 # Though this won't be called by syntax errors in the input line,
1518 1568 # there may be SyntaxError cases whith imported code.
1519 1569
1520 1570 try:
1521 1571 if exc_tuple is None:
1522 1572 etype, value, tb = sys.exc_info()
1523 1573 else:
1524 1574 etype, value, tb = exc_tuple
1525 1575
1526 1576 if etype is SyntaxError:
1527 1577 self.showsyntaxerror(filename)
1528 1578 elif etype is IPython.ipapi.UsageError:
1529 1579 print "UsageError:", value
1530 1580 else:
1531 1581 # WARNING: these variables are somewhat deprecated and not
1532 1582 # necessarily safe to use in a threaded environment, but tools
1533 1583 # like pdb depend on their existence, so let's set them. If we
1534 1584 # find problems in the field, we'll need to revisit their use.
1535 1585 sys.last_type = etype
1536 1586 sys.last_value = value
1537 1587 sys.last_traceback = tb
1538 1588
1539 1589 if etype in self.custom_exceptions:
1540 1590 self.CustomTB(etype,value,tb)
1541 1591 else:
1542 1592 self.InteractiveTB(etype,value,tb,tb_offset=tb_offset)
1543 1593 if self.InteractiveTB.call_pdb and self.has_readline:
1544 1594 # pdb mucks up readline, fix it back
1545 1595 self.set_completer()
1546 1596 except KeyboardInterrupt:
1547 1597 self.write("\nKeyboardInterrupt\n")
1548
1549
1550 1598
1551 1599 def mainloop(self,banner=None):
1552 1600 """Creates the local namespace and starts the mainloop.
1553 1601
1554 1602 If an optional banner argument is given, it will override the
1555 1603 internally created default banner."""
1556 1604
1557 1605 if self.rc.c: # Emulate Python's -c option
1558 1606 self.exec_init_cmd()
1559 1607 if banner is None:
1560 1608 if not self.rc.banner:
1561 1609 banner = ''
1562 1610 # banner is string? Use it directly!
1563 1611 elif isinstance(self.rc.banner,basestring):
1564 1612 banner = self.rc.banner
1565 1613 else:
1566 1614 banner = self.BANNER+self.banner2
1567 1615
1568 1616 while 1:
1569 1617 try:
1570 1618 self.interact(banner)
1571 1619 #self.interact_with_readline()
1572 # XXX for testing of a readline-decoupled repl loop, call interact_with_readline above
1620
1621 # XXX for testing of a readline-decoupled repl loop, call
1622 # interact_with_readline above
1573 1623
1574 1624 break
1575 1625 except KeyboardInterrupt:
1576 1626 # this should not be necessary, but KeyboardInterrupt
1577 1627 # handling seems rather unpredictable...
1578 1628 self.write("\nKeyboardInterrupt in interact()\n")
1579 1629
1580 1630 def exec_init_cmd(self):
1581 1631 """Execute a command given at the command line.
1582 1632
1583 1633 This emulates Python's -c option."""
1584 1634
1585 1635 #sys.argv = ['-c']
1586 1636 self.push(self.prefilter(self.rc.c, False))
1587 1637 if not self.rc.interact:
1588 1638 self.ask_exit()
1589 1639
1590 1640 def embed_mainloop(self,header='',local_ns=None,global_ns=None,stack_depth=0):
1591 1641 """Embeds IPython into a running python program.
1592 1642
1593 1643 Input:
1594 1644
1595 1645 - header: An optional header message can be specified.
1596 1646
1597 1647 - local_ns, global_ns: working namespaces. If given as None, the
1598 1648 IPython-initialized one is updated with __main__.__dict__, so that
1599 1649 program variables become visible but user-specific configuration
1600 1650 remains possible.
1601 1651
1602 1652 - stack_depth: specifies how many levels in the stack to go to
1603 1653 looking for namespaces (when local_ns and global_ns are None). This
1604 1654 allows an intermediate caller to make sure that this function gets
1605 1655 the namespace from the intended level in the stack. By default (0)
1606 1656 it will get its locals and globals from the immediate caller.
1607 1657
1608 1658 Warning: it's possible to use this in a program which is being run by
1609 1659 IPython itself (via %run), but some funny things will happen (a few
1610 1660 globals get overwritten). In the future this will be cleaned up, as
1611 1661 there is no fundamental reason why it can't work perfectly."""
1612 1662
1613 1663 # Get locals and globals from caller
1614 1664 if local_ns is None or global_ns is None:
1615 1665 call_frame = sys._getframe(stack_depth).f_back
1616 1666
1617 1667 if local_ns is None:
1618 1668 local_ns = call_frame.f_locals
1619 1669 if global_ns is None:
1620 1670 global_ns = call_frame.f_globals
1621 1671
1622 1672 # Update namespaces and fire up interpreter
1623 1673
1624 1674 # The global one is easy, we can just throw it in
1625 1675 self.user_global_ns = global_ns
1626 1676
1627 1677 # but the user/local one is tricky: ipython needs it to store internal
1628 1678 # data, but we also need the locals. We'll copy locals in the user
1629 1679 # one, but will track what got copied so we can delete them at exit.
1630 1680 # This is so that a later embedded call doesn't see locals from a
1631 1681 # previous call (which most likely existed in a separate scope).
1632 1682 local_varnames = local_ns.keys()
1633 1683 self.user_ns.update(local_ns)
1634 1684 #self.user_ns['local_ns'] = local_ns # dbg
1635 1685
1636 1686 # Patch for global embedding to make sure that things don't overwrite
1637 1687 # user globals accidentally. Thanks to Richard <rxe@renre-europe.com>
1638 1688 # FIXME. Test this a bit more carefully (the if.. is new)
1639 1689 if local_ns is None and global_ns is None:
1640 1690 self.user_global_ns.update(__main__.__dict__)
1641 1691
1642 1692 # make sure the tab-completer has the correct frame information, so it
1643 1693 # actually completes using the frame's locals/globals
1644 1694 self.set_completer_frame()
1645 1695
1646 1696 # before activating the interactive mode, we need to make sure that
1647 1697 # all names in the builtin namespace needed by ipython point to
1648 1698 # ourselves, and not to other instances.
1649 1699 self.add_builtins()
1650 1700
1651 1701 self.interact(header)
1652 1702
1653 1703 # now, purge out the user namespace from anything we might have added
1654 1704 # from the caller's local namespace
1655 1705 delvar = self.user_ns.pop
1656 1706 for var in local_varnames:
1657 1707 delvar(var,None)
1658 1708 # and clean builtins we may have overridden
1659 1709 self.clean_builtins()
1660 1710
1661 1711 def interact_prompt(self):
1662 1712 """ Print the prompt (in read-eval-print loop)
1663 1713
1664 1714 Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not
1665 1715 used in standard IPython flow.
1666 1716 """
1667 1717 if self.more:
1668 1718 try:
1669 1719 prompt = self.hooks.generate_prompt(True)
1670 1720 except:
1671 1721 self.showtraceback()
1672 1722 if self.autoindent:
1673 1723 self.rl_do_indent = True
1674 1724
1675 1725 else:
1676 1726 try:
1677 1727 prompt = self.hooks.generate_prompt(False)
1678 1728 except:
1679 1729 self.showtraceback()
1680 1730 self.write(prompt)
1681 1731
1682 1732 def interact_handle_input(self,line):
1683 1733 """ Handle the input line (in read-eval-print loop)
1684 1734
1685 1735 Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not
1686 1736 used in standard IPython flow.
1687 1737 """
1688 1738 if line.lstrip() == line:
1689 1739 self.shadowhist.add(line.strip())
1690 1740 lineout = self.prefilter(line,self.more)
1691 1741
1692 1742 if line.strip():
1693 1743 if self.more:
1694 1744 self.input_hist_raw[-1] += '%s\n' % line
1695 1745 else:
1696 1746 self.input_hist_raw.append('%s\n' % line)
1697 1747
1698 1748
1699 1749 self.more = self.push(lineout)
1700 1750 if (self.SyntaxTB.last_syntax_error and
1701 1751 self.rc.autoedit_syntax):
1702 1752 self.edit_syntax_error()
1703 1753
1704 1754 def interact_with_readline(self):
1705 1755 """ Demo of using interact_handle_input, interact_prompt
1706 1756
1707 1757 This is the main read-eval-print loop. If you need to implement your own (e.g. for GUI),
1708 1758 it should work like this.
1709 1759 """
1710 1760 self.readline_startup_hook(self.pre_readline)
1711 1761 while not self.exit_now:
1712 1762 self.interact_prompt()
1713 1763 if self.more:
1714 1764 self.rl_do_indent = True
1715 1765 else:
1716 1766 self.rl_do_indent = False
1717 1767 line = raw_input_original().decode(self.stdin_encoding)
1718 1768 self.interact_handle_input(line)
1719 1769
1720 1770
1721 1771 def interact(self, banner=None):
1722 1772 """Closely emulate the interactive Python console.
1723 1773
1724 1774 The optional banner argument specify the banner to print
1725 1775 before the first interaction; by default it prints a banner
1726 1776 similar to the one printed by the real Python interpreter,
1727 1777 followed by the current class name in parentheses (so as not
1728 1778 to confuse this with the real interpreter -- since it's so
1729 1779 close!).
1730 1780
1731 1781 """
1732 1782
1733 1783 if self.exit_now:
1734 1784 # batch run -> do not interact
1735 1785 return
1736 1786 cprt = 'Type "copyright", "credits" or "license" for more information.'
1737 1787 if banner is None:
1738 1788 self.write("Python %s on %s\n%s\n(%s)\n" %
1739 1789 (sys.version, sys.platform, cprt,
1740 1790 self.__class__.__name__))
1741 1791 else:
1742 1792 self.write(banner)
1743 1793
1744 1794 more = 0
1745 1795
1746 1796 # Mark activity in the builtins
1747 1797 __builtin__.__dict__['__IPYTHON__active'] += 1
1748 1798
1749 1799 if self.has_readline:
1750 1800 self.readline_startup_hook(self.pre_readline)
1751 1801 # exit_now is set by a call to %Exit or %Quit, through the
1752 1802 # ask_exit callback.
1753 1803
1754 1804 while not self.exit_now:
1755 1805 self.hooks.pre_prompt_hook()
1756 1806 if more:
1757 1807 try:
1758 1808 prompt = self.hooks.generate_prompt(True)
1759 1809 except:
1760 1810 self.showtraceback()
1761 1811 if self.autoindent:
1762 1812 self.rl_do_indent = True
1763 1813
1764 1814 else:
1765 1815 try:
1766 1816 prompt = self.hooks.generate_prompt(False)
1767 1817 except:
1768 1818 self.showtraceback()
1769 1819 try:
1770 1820 line = self.raw_input(prompt,more)
1771 1821 if self.exit_now:
1772 1822 # quick exit on sys.std[in|out] close
1773 1823 break
1774 1824 if self.autoindent:
1775 1825 self.rl_do_indent = False
1776 1826
1777 1827 except KeyboardInterrupt:
1778 1828 #double-guard against keyboardinterrupts during kbdint handling
1779 1829 try:
1780 1830 self.write('\nKeyboardInterrupt\n')
1781 1831 self.resetbuffer()
1782 1832 # keep cache in sync with the prompt counter:
1783 1833 self.outputcache.prompt_count -= 1
1784 1834
1785 1835 if self.autoindent:
1786 1836 self.indent_current_nsp = 0
1787 1837 more = 0
1788 1838 except KeyboardInterrupt:
1789 1839 pass
1790 1840 except EOFError:
1791 1841 if self.autoindent:
1792 1842 self.rl_do_indent = False
1793 1843 self.readline_startup_hook(None)
1794 1844 self.write('\n')
1795 1845 self.exit()
1796 1846 except bdb.BdbQuit:
1797 1847 warn('The Python debugger has exited with a BdbQuit exception.\n'
1798 1848 'Because of how pdb handles the stack, it is impossible\n'
1799 1849 'for IPython to properly format this particular exception.\n'
1800 1850 'IPython will resume normal operation.')
1801 1851 except:
1802 1852 # exceptions here are VERY RARE, but they can be triggered
1803 1853 # asynchronously by signal handlers, for example.
1804 1854 self.showtraceback()
1805 1855 else:
1806 1856 more = self.push(line)
1807 1857 if (self.SyntaxTB.last_syntax_error and
1808 1858 self.rc.autoedit_syntax):
1809 1859 self.edit_syntax_error()
1810 1860
1811 1861 # We are off again...
1812 1862 __builtin__.__dict__['__IPYTHON__active'] -= 1
1813 1863
1814 1864 def excepthook(self, etype, value, tb):
1815 1865 """One more defense for GUI apps that call sys.excepthook.
1816 1866
1817 1867 GUI frameworks like wxPython trap exceptions and call
1818 1868 sys.excepthook themselves. I guess this is a feature that
1819 1869 enables them to keep running after exceptions that would
1820 1870 otherwise kill their mainloop. This is a bother for IPython
1821 1871 which excepts to catch all of the program exceptions with a try:
1822 1872 except: statement.
1823 1873
1824 1874 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1825 1875 any app directly invokes sys.excepthook, it will look to the user like
1826 1876 IPython crashed. In order to work around this, we can disable the
1827 1877 CrashHandler and replace it with this excepthook instead, which prints a
1828 1878 regular traceback using our InteractiveTB. In this fashion, apps which
1829 1879 call sys.excepthook will generate a regular-looking exception from
1830 1880 IPython, and the CrashHandler will only be triggered by real IPython
1831 1881 crashes.
1832 1882
1833 1883 This hook should be used sparingly, only in places which are not likely
1834 1884 to be true IPython errors.
1835 1885 """
1836 1886 self.showtraceback((etype,value,tb),tb_offset=0)
1837 1887
1838 1888 def expand_aliases(self,fn,rest):
1839 1889 """ Expand multiple levels of aliases:
1840 1890
1841 1891 if:
1842 1892
1843 1893 alias foo bar /tmp
1844 1894 alias baz foo
1845 1895
1846 1896 then:
1847 1897
1848 1898 baz huhhahhei -> bar /tmp huhhahhei
1849 1899
1850 1900 """
1851 1901 line = fn + " " + rest
1852 1902
1853 1903 done = Set()
1854 1904 while 1:
1855 1905 pre,fn,rest = prefilter.splitUserInput(line,
1856 1906 prefilter.shell_line_split)
1857 1907 if fn in self.alias_table:
1858 1908 if fn in done:
1859 1909 warn("Cyclic alias definition, repeated '%s'" % fn)
1860 1910 return ""
1861 1911 done.add(fn)
1862 1912
1863 1913 l2 = self.transform_alias(fn,rest)
1864 1914 # dir -> dir
1865 1915 # print "alias",line, "->",l2 #dbg
1866 1916 if l2 == line:
1867 1917 break
1868 1918 # ls -> ls -F should not recurse forever
1869 1919 if l2.split(None,1)[0] == line.split(None,1)[0]:
1870 1920 line = l2
1871 1921 break
1872 1922
1873 1923 line=l2
1874 1924
1875 1925
1876 1926 # print "al expand to",line #dbg
1877 1927 else:
1878 1928 break
1879 1929
1880 1930 return line
1881 1931
1882 1932 def transform_alias(self, alias,rest=''):
1883 1933 """ Transform alias to system command string.
1884 1934 """
1885 1935 trg = self.alias_table[alias]
1886 1936
1887 1937 nargs,cmd = trg
1888 1938 # print trg #dbg
1889 1939 if ' ' in cmd and os.path.isfile(cmd):
1890 1940 cmd = '"%s"' % cmd
1891 1941
1892 1942 # Expand the %l special to be the user's input line
1893 1943 if cmd.find('%l') >= 0:
1894 1944 cmd = cmd.replace('%l',rest)
1895 1945 rest = ''
1896 1946 if nargs==0:
1897 1947 # Simple, argument-less aliases
1898 1948 cmd = '%s %s' % (cmd,rest)
1899 1949 else:
1900 1950 # Handle aliases with positional arguments
1901 1951 args = rest.split(None,nargs)
1902 1952 if len(args)< nargs:
1903 1953 error('Alias <%s> requires %s arguments, %s given.' %
1904 1954 (alias,nargs,len(args)))
1905 1955 return None
1906 1956 cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:]))
1907 1957 # Now call the macro, evaluating in the user's namespace
1908 1958 #print 'new command: <%r>' % cmd # dbg
1909 1959 return cmd
1910 1960
1911 1961 def call_alias(self,alias,rest=''):
1912 1962 """Call an alias given its name and the rest of the line.
1913 1963
1914 1964 This is only used to provide backwards compatibility for users of
1915 1965 ipalias(), use of which is not recommended for anymore."""
1916 1966
1917 1967 # Now call the macro, evaluating in the user's namespace
1918 1968 cmd = self.transform_alias(alias, rest)
1919 1969 try:
1920 1970 self.system(cmd)
1921 1971 except:
1922 1972 self.showtraceback()
1923 1973
1924 1974 def indent_current_str(self):
1925 1975 """return the current level of indentation as a string"""
1926 1976 return self.indent_current_nsp * ' '
1927 1977
1928 1978 def autoindent_update(self,line):
1929 1979 """Keep track of the indent level."""
1930 1980
1931 1981 #debugx('line')
1932 1982 #debugx('self.indent_current_nsp')
1933 1983 if self.autoindent:
1934 1984 if line:
1935 1985 inisp = num_ini_spaces(line)
1936 1986 if inisp < self.indent_current_nsp:
1937 1987 self.indent_current_nsp = inisp
1938 1988
1939 1989 if line[-1] == ':':
1940 1990 self.indent_current_nsp += 4
1941 1991 elif dedent_re.match(line):
1942 1992 self.indent_current_nsp -= 4
1943 1993 else:
1944 1994 self.indent_current_nsp = 0
1945 1995
1946 1996 def runlines(self,lines):
1947 1997 """Run a string of one or more lines of source.
1948 1998
1949 1999 This method is capable of running a string containing multiple source
1950 2000 lines, as if they had been entered at the IPython prompt. Since it
1951 2001 exposes IPython's processing machinery, the given strings can contain
1952 2002 magic calls (%magic), special shell access (!cmd), etc."""
1953 2003
1954 2004 # We must start with a clean buffer, in case this is run from an
1955 2005 # interactive IPython session (via a magic, for example).
1956 2006 self.resetbuffer()
1957 2007 lines = lines.split('\n')
1958 2008 more = 0
1959 2009
1960 2010 for line in lines:
1961 2011 # skip blank lines so we don't mess up the prompt counter, but do
1962 2012 # NOT skip even a blank line if we are in a code block (more is
1963 2013 # true)
1964 2014
1965 2015
1966 2016 if line or more:
1967 2017 # push to raw history, so hist line numbers stay in sync
1968 2018 self.input_hist_raw.append("# " + line + "\n")
1969 2019 more = self.push(self.prefilter(line,more))
1970 2020 # IPython's runsource returns None if there was an error
1971 2021 # compiling the code. This allows us to stop processing right
1972 2022 # away, so the user gets the error message at the right place.
1973 2023 if more is None:
1974 2024 break
1975 2025 else:
1976 2026 self.input_hist_raw.append("\n")
1977 2027 # final newline in case the input didn't have it, so that the code
1978 2028 # actually does get executed
1979 2029 if more:
1980 2030 self.push('\n')
1981 2031
1982 2032 def runsource(self, source, filename='<input>', symbol='single'):
1983 2033 """Compile and run some source in the interpreter.
1984 2034
1985 2035 Arguments are as for compile_command().
1986 2036
1987 2037 One several things can happen:
1988 2038
1989 2039 1) The input is incorrect; compile_command() raised an
1990 2040 exception (SyntaxError or OverflowError). A syntax traceback
1991 2041 will be printed by calling the showsyntaxerror() method.
1992 2042
1993 2043 2) The input is incomplete, and more input is required;
1994 2044 compile_command() returned None. Nothing happens.
1995 2045
1996 2046 3) The input is complete; compile_command() returned a code
1997 2047 object. The code is executed by calling self.runcode() (which
1998 2048 also handles run-time exceptions, except for SystemExit).
1999 2049
2000 2050 The return value is:
2001 2051
2002 2052 - True in case 2
2003 2053
2004 2054 - False in the other cases, unless an exception is raised, where
2005 2055 None is returned instead. This can be used by external callers to
2006 2056 know whether to continue feeding input or not.
2007 2057
2008 2058 The return value can be used to decide whether to use sys.ps1 or
2009 2059 sys.ps2 to prompt the next line."""
2010 2060
2011 2061 # if the source code has leading blanks, add 'if 1:\n' to it
2012 2062 # this allows execution of indented pasted code. It is tempting
2013 2063 # to add '\n' at the end of source to run commands like ' a=1'
2014 2064 # directly, but this fails for more complicated scenarios
2015 2065 source=source.encode(self.stdin_encoding)
2016 2066 if source[:1] in [' ', '\t']:
2017 2067 source = 'if 1:\n%s' % source
2018 2068
2019 2069 try:
2020 2070 code = self.compile(source,filename,symbol)
2021 2071 except (OverflowError, SyntaxError, ValueError, TypeError):
2022 2072 # Case 1
2023 2073 self.showsyntaxerror(filename)
2024 2074 return None
2025 2075
2026 2076 if code is None:
2027 2077 # Case 2
2028 2078 return True
2029 2079
2030 2080 # Case 3
2031 2081 # We store the code object so that threaded shells and
2032 2082 # custom exception handlers can access all this info if needed.
2033 2083 # The source corresponding to this can be obtained from the
2034 2084 # buffer attribute as '\n'.join(self.buffer).
2035 2085 self.code_to_run = code
2036 2086 # now actually execute the code object
2037 2087 if self.runcode(code) == 0:
2038 2088 return False
2039 2089 else:
2040 2090 return None
2041 2091
2042 2092 def runcode(self,code_obj):
2043 2093 """Execute a code object.
2044 2094
2045 2095 When an exception occurs, self.showtraceback() is called to display a
2046 2096 traceback.
2047 2097
2048 2098 Return value: a flag indicating whether the code to be run completed
2049 2099 successfully:
2050 2100
2051 2101 - 0: successful execution.
2052 2102 - 1: an error occurred.
2053 2103 """
2054 2104
2055 2105 # Set our own excepthook in case the user code tries to call it
2056 2106 # directly, so that the IPython crash handler doesn't get triggered
2057 2107 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
2058 2108
2059 2109 # we save the original sys.excepthook in the instance, in case config
2060 2110 # code (such as magics) needs access to it.
2061 2111 self.sys_excepthook = old_excepthook
2062 2112 outflag = 1 # happens in more places, so it's easier as default
2063 2113 try:
2064 2114 try:
2065 2115 self.hooks.pre_runcode_hook()
2066 2116 exec code_obj in self.user_global_ns, self.user_ns
2067 2117 finally:
2068 2118 # Reset our crash handler in place
2069 2119 sys.excepthook = old_excepthook
2070 2120 except SystemExit:
2071 2121 self.resetbuffer()
2072 2122 self.showtraceback()
2073 2123 warn("Type %exit or %quit to exit IPython "
2074 2124 "(%Exit or %Quit do so unconditionally).",level=1)
2075 2125 except self.custom_exceptions:
2076 2126 etype,value,tb = sys.exc_info()
2077 2127 self.CustomTB(etype,value,tb)
2078 2128 except:
2079 2129 self.showtraceback()
2080 2130 else:
2081 2131 outflag = 0
2082 2132 if softspace(sys.stdout, 0):
2083 2133 print
2084 2134 # Flush out code object which has been run (and source)
2085 2135 self.code_to_run = None
2086 2136 return outflag
2087 2137
2088 2138 def push(self, line):
2089 2139 """Push a line to the interpreter.
2090 2140
2091 2141 The line should not have a trailing newline; it may have
2092 2142 internal newlines. The line is appended to a buffer and the
2093 2143 interpreter's runsource() method is called with the
2094 2144 concatenated contents of the buffer as source. If this
2095 2145 indicates that the command was executed or invalid, the buffer
2096 2146 is reset; otherwise, the command is incomplete, and the buffer
2097 2147 is left as it was after the line was appended. The return
2098 2148 value is 1 if more input is required, 0 if the line was dealt
2099 2149 with in some way (this is the same as runsource()).
2100 2150 """
2101 2151
2102 2152 # autoindent management should be done here, and not in the
2103 2153 # interactive loop, since that one is only seen by keyboard input. We
2104 2154 # need this done correctly even for code run via runlines (which uses
2105 2155 # push).
2106 2156
2107 2157 #print 'push line: <%s>' % line # dbg
2108 2158 for subline in line.splitlines():
2109 2159 self.autoindent_update(subline)
2110 2160 self.buffer.append(line)
2111 2161 more = self.runsource('\n'.join(self.buffer), self.filename)
2112 2162 if not more:
2113 2163 self.resetbuffer()
2114 2164 return more
2115 2165
2116 2166 def split_user_input(self, line):
2117 2167 # This is really a hold-over to support ipapi and some extensions
2118 2168 return prefilter.splitUserInput(line)
2119 2169
2120 2170 def resetbuffer(self):
2121 2171 """Reset the input buffer."""
2122 2172 self.buffer[:] = []
2123 2173
2124 2174 def raw_input(self,prompt='',continue_prompt=False):
2125 2175 """Write a prompt and read a line.
2126 2176
2127 2177 The returned line does not include the trailing newline.
2128 2178 When the user enters the EOF key sequence, EOFError is raised.
2129 2179
2130 2180 Optional inputs:
2131 2181
2132 2182 - prompt(''): a string to be printed to prompt the user.
2133 2183
2134 2184 - continue_prompt(False): whether this line is the first one or a
2135 2185 continuation in a sequence of inputs.
2136 2186 """
2137 2187
2138 2188 # Code run by the user may have modified the readline completer state.
2139 2189 # We must ensure that our completer is back in place.
2140 2190 if self.has_readline:
2141 2191 self.set_completer()
2142 2192
2143 2193 try:
2144 2194 line = raw_input_original(prompt).decode(self.stdin_encoding)
2145 2195 except ValueError:
2146 2196 warn("\n********\nYou or a %run:ed script called sys.stdin.close()"
2147 2197 " or sys.stdout.close()!\nExiting IPython!")
2148 2198 self.ask_exit()
2149 2199 return ""
2150 2200
2151 2201 # Try to be reasonably smart about not re-indenting pasted input more
2152 2202 # than necessary. We do this by trimming out the auto-indent initial
2153 2203 # spaces, if the user's actual input started itself with whitespace.
2154 2204 #debugx('self.buffer[-1]')
2155 2205
2156 2206 if self.autoindent:
2157 2207 if num_ini_spaces(line) > self.indent_current_nsp:
2158 2208 line = line[self.indent_current_nsp:]
2159 2209 self.indent_current_nsp = 0
2160 2210
2161 2211 # store the unfiltered input before the user has any chance to modify
2162 2212 # it.
2163 2213 if line.strip():
2164 2214 if continue_prompt:
2165 2215 self.input_hist_raw[-1] += '%s\n' % line
2166 2216 if self.has_readline: # and some config option is set?
2167 2217 try:
2168 2218 histlen = self.readline.get_current_history_length()
2169 2219 if histlen > 1:
2170 2220 newhist = self.input_hist_raw[-1].rstrip()
2171 2221 self.readline.remove_history_item(histlen-1)
2172 2222 self.readline.replace_history_item(histlen-2,
2173 2223 newhist.encode(self.stdin_encoding))
2174 2224 except AttributeError:
2175 2225 pass # re{move,place}_history_item are new in 2.4.
2176 2226 else:
2177 2227 self.input_hist_raw.append('%s\n' % line)
2178 2228 # only entries starting at first column go to shadow history
2179 2229 if line.lstrip() == line:
2180 2230 self.shadowhist.add(line.strip())
2181 2231 elif not continue_prompt:
2182 2232 self.input_hist_raw.append('\n')
2183 2233 try:
2184 2234 lineout = self.prefilter(line,continue_prompt)
2185 2235 except:
2186 2236 # blanket except, in case a user-defined prefilter crashes, so it
2187 2237 # can't take all of ipython with it.
2188 2238 self.showtraceback()
2189 2239 return ''
2190 2240 else:
2191 2241 return lineout
2192 2242
2193 2243 def _prefilter(self, line, continue_prompt):
2194 2244 """Calls different preprocessors, depending on the form of line."""
2195 2245
2196 2246 # All handlers *must* return a value, even if it's blank ('').
2197 2247
2198 2248 # Lines are NOT logged here. Handlers should process the line as
2199 2249 # needed, update the cache AND log it (so that the input cache array
2200 2250 # stays synced).
2201 2251
2202 2252 #.....................................................................
2203 2253 # Code begins
2204 2254
2205 2255 #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg
2206 2256
2207 2257 # save the line away in case we crash, so the post-mortem handler can
2208 2258 # record it
2209 2259 self._last_input_line = line
2210 2260
2211 2261 #print '***line: <%s>' % line # dbg
2212 2262
2213 2263 if not line:
2214 2264 # Return immediately on purely empty lines, so that if the user
2215 2265 # previously typed some whitespace that started a continuation
2216 2266 # prompt, he can break out of that loop with just an empty line.
2217 2267 # This is how the default python prompt works.
2218 2268
2219 2269 # Only return if the accumulated input buffer was just whitespace!
2220 2270 if ''.join(self.buffer).isspace():
2221 2271 self.buffer[:] = []
2222 2272 return ''
2223 2273
2224 2274 line_info = prefilter.LineInfo(line, continue_prompt)
2225 2275
2226 2276 # the input history needs to track even empty lines
2227 2277 stripped = line.strip()
2228 2278
2229 2279 if not stripped:
2230 2280 if not continue_prompt:
2231 2281 self.outputcache.prompt_count -= 1
2232 2282 return self.handle_normal(line_info)
2233 2283
2234 2284 # print '***cont',continue_prompt # dbg
2235 2285 # special handlers are only allowed for single line statements
2236 2286 if continue_prompt and not self.rc.multi_line_specials:
2237 2287 return self.handle_normal(line_info)
2238 2288
2239 2289
2240 2290 # See whether any pre-existing handler can take care of it
2241 2291 rewritten = self.hooks.input_prefilter(stripped)
2242 2292 if rewritten != stripped: # ok, some prefilter did something
2243 2293 rewritten = line_info.pre + rewritten # add indentation
2244 2294 return self.handle_normal(prefilter.LineInfo(rewritten,
2245 2295 continue_prompt))
2246 2296
2247 2297 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
2248 2298
2249 2299 return prefilter.prefilter(line_info, self)
2250 2300
2251 2301
2252 2302 def _prefilter_dumb(self, line, continue_prompt):
2253 2303 """simple prefilter function, for debugging"""
2254 2304 return self.handle_normal(line,continue_prompt)
2255 2305
2256 2306
2257 2307 def multiline_prefilter(self, line, continue_prompt):
2258 2308 """ Run _prefilter for each line of input
2259 2309
2260 2310 Covers cases where there are multiple lines in the user entry,
2261 2311 which is the case when the user goes back to a multiline history
2262 2312 entry and presses enter.
2263 2313
2264 2314 """
2265 2315 out = []
2266 2316 for l in line.rstrip('\n').split('\n'):
2267 2317 out.append(self._prefilter(l, continue_prompt))
2268 2318 return '\n'.join(out)
2269 2319
2270 2320 # Set the default prefilter() function (this can be user-overridden)
2271 2321 prefilter = multiline_prefilter
2272 2322
2273 2323 def handle_normal(self,line_info):
2274 2324 """Handle normal input lines. Use as a template for handlers."""
2275 2325
2276 2326 # With autoindent on, we need some way to exit the input loop, and I
2277 2327 # don't want to force the user to have to backspace all the way to
2278 2328 # clear the line. The rule will be in this case, that either two
2279 2329 # lines of pure whitespace in a row, or a line of pure whitespace but
2280 2330 # of a size different to the indent level, will exit the input loop.
2281 2331 line = line_info.line
2282 2332 continue_prompt = line_info.continue_prompt
2283 2333
2284 2334 if (continue_prompt and self.autoindent and line.isspace() and
2285 2335 (0 < abs(len(line) - self.indent_current_nsp) <= 2 or
2286 2336 (self.buffer[-1]).isspace() )):
2287 2337 line = ''
2288 2338
2289 2339 self.log(line,line,continue_prompt)
2290 2340 return line
2291 2341
2292 2342 def handle_alias(self,line_info):
2293 2343 """Handle alias input lines. """
2294 2344 tgt = self.alias_table[line_info.iFun]
2295 2345 # print "=>",tgt #dbg
2296 2346 if callable(tgt):
2297 2347 if '$' in line_info.line:
2298 2348 call_meth = '(_ip, _ip.itpl(%s))'
2299 2349 else:
2300 2350 call_meth = '(_ip,%s)'
2301 2351 line_out = ("%s_sh.%s" + call_meth) % (line_info.preWhitespace,
2302 2352 line_info.iFun,
2303 2353 make_quoted_expr(line_info.line))
2304 2354 else:
2305 2355 transformed = self.expand_aliases(line_info.iFun,line_info.theRest)
2306 2356
2307 2357 # pre is needed, because it carries the leading whitespace. Otherwise
2308 2358 # aliases won't work in indented sections.
2309 2359 line_out = '%s_ip.system(%s)' % (line_info.preWhitespace,
2310 2360 make_quoted_expr( transformed ))
2311 2361
2312 2362 self.log(line_info.line,line_out,line_info.continue_prompt)
2313 2363 #print 'line out:',line_out # dbg
2314 2364 return line_out
2315 2365
2316 2366 def handle_shell_escape(self, line_info):
2317 2367 """Execute the line in a shell, empty return value"""
2318 2368 #print 'line in :', `line` # dbg
2319 2369 line = line_info.line
2320 2370 if line.lstrip().startswith('!!'):
2321 2371 # rewrite LineInfo's line, iFun and theRest to properly hold the
2322 2372 # call to %sx and the actual command to be executed, so
2323 2373 # handle_magic can work correctly. Note that this works even if
2324 2374 # the line is indented, so it handles multi_line_specials
2325 2375 # properly.
2326 2376 new_rest = line.lstrip()[2:]
2327 2377 line_info.line = '%ssx %s' % (self.ESC_MAGIC,new_rest)
2328 2378 line_info.iFun = 'sx'
2329 2379 line_info.theRest = new_rest
2330 2380 return self.handle_magic(line_info)
2331 2381 else:
2332 2382 cmd = line.lstrip().lstrip('!')
2333 2383 line_out = '%s_ip.system(%s)' % (line_info.preWhitespace,
2334 2384 make_quoted_expr(cmd))
2335 2385 # update cache/log and return
2336 2386 self.log(line,line_out,line_info.continue_prompt)
2337 2387 return line_out
2338 2388
2339 2389 def handle_magic(self, line_info):
2340 2390 """Execute magic functions."""
2341 2391 iFun = line_info.iFun
2342 2392 theRest = line_info.theRest
2343 2393 cmd = '%s_ip.magic(%s)' % (line_info.preWhitespace,
2344 2394 make_quoted_expr(iFun + " " + theRest))
2345 2395 self.log(line_info.line,cmd,line_info.continue_prompt)
2346 2396 #print 'in handle_magic, cmd=<%s>' % cmd # dbg
2347 2397 return cmd
2348 2398
2349 2399 def handle_auto(self, line_info):
2350 2400 """Hande lines which can be auto-executed, quoting if requested."""
2351 2401
2352 2402 line = line_info.line
2353 2403 iFun = line_info.iFun
2354 2404 theRest = line_info.theRest
2355 2405 pre = line_info.pre
2356 2406 continue_prompt = line_info.continue_prompt
2357 2407 obj = line_info.ofind(self)['obj']
2358 2408
2359 2409 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
2360 2410
2361 2411 # This should only be active for single-line input!
2362 2412 if continue_prompt:
2363 2413 self.log(line,line,continue_prompt)
2364 2414 return line
2365 2415
2366 2416 force_auto = isinstance(obj, IPython.ipapi.IPyAutocall)
2367 2417 auto_rewrite = True
2368 2418
2369 2419 if pre == self.ESC_QUOTE:
2370 2420 # Auto-quote splitting on whitespace
2371 2421 newcmd = '%s("%s")' % (iFun,'", "'.join(theRest.split()) )
2372 2422 elif pre == self.ESC_QUOTE2:
2373 2423 # Auto-quote whole string
2374 2424 newcmd = '%s("%s")' % (iFun,theRest)
2375 2425 elif pre == self.ESC_PAREN:
2376 2426 newcmd = '%s(%s)' % (iFun,",".join(theRest.split()))
2377 2427 else:
2378 2428 # Auto-paren.
2379 2429 # We only apply it to argument-less calls if the autocall
2380 2430 # parameter is set to 2. We only need to check that autocall is <
2381 2431 # 2, since this function isn't called unless it's at least 1.
2382 2432 if not theRest and (self.rc.autocall < 2) and not force_auto:
2383 2433 newcmd = '%s %s' % (iFun,theRest)
2384 2434 auto_rewrite = False
2385 2435 else:
2386 2436 if not force_auto and theRest.startswith('['):
2387 2437 if hasattr(obj,'__getitem__'):
2388 2438 # Don't autocall in this case: item access for an object
2389 2439 # which is BOTH callable and implements __getitem__.
2390 2440 newcmd = '%s %s' % (iFun,theRest)
2391 2441 auto_rewrite = False
2392 2442 else:
2393 2443 # if the object doesn't support [] access, go ahead and
2394 2444 # autocall
2395 2445 newcmd = '%s(%s)' % (iFun.rstrip(),theRest)
2396 2446 elif theRest.endswith(';'):
2397 2447 newcmd = '%s(%s);' % (iFun.rstrip(),theRest[:-1])
2398 2448 else:
2399 2449 newcmd = '%s(%s)' % (iFun.rstrip(), theRest)
2400 2450
2401 2451 if auto_rewrite:
2402 2452 rw = self.outputcache.prompt1.auto_rewrite() + newcmd
2403 2453
2404 2454 try:
2405 2455 # plain ascii works better w/ pyreadline, on some machines, so
2406 2456 # we use it and only print uncolored rewrite if we have unicode
2407 2457 rw = str(rw)
2408 2458 print >>Term.cout, rw
2409 2459 except UnicodeEncodeError:
2410 2460 print "-------------->" + newcmd
2411 2461
2412 2462 # log what is now valid Python, not the actual user input (without the
2413 2463 # final newline)
2414 2464 self.log(line,newcmd,continue_prompt)
2415 2465 return newcmd
2416 2466
2417 2467 def handle_help(self, line_info):
2418 2468 """Try to get some help for the object.
2419 2469
2420 2470 obj? or ?obj -> basic information.
2421 2471 obj?? or ??obj -> more details.
2422 2472 """
2423 2473
2424 2474 line = line_info.line
2425 2475 # We need to make sure that we don't process lines which would be
2426 2476 # otherwise valid python, such as "x=1 # what?"
2427 2477 try:
2428 2478 codeop.compile_command(line)
2429 2479 except SyntaxError:
2430 2480 # We should only handle as help stuff which is NOT valid syntax
2431 2481 if line[0]==self.ESC_HELP:
2432 2482 line = line[1:]
2433 2483 elif line[-1]==self.ESC_HELP:
2434 2484 line = line[:-1]
2435 2485 self.log(line,'#?'+line,line_info.continue_prompt)
2436 2486 if line:
2437 2487 #print 'line:<%r>' % line # dbg
2438 2488 self.magic_pinfo(line)
2439 2489 else:
2440 2490 page(self.usage,screen_lines=self.rc.screen_length)
2441 2491 return '' # Empty string is needed here!
2442 2492 except:
2443 2493 # Pass any other exceptions through to the normal handler
2444 2494 return self.handle_normal(line_info)
2445 2495 else:
2446 2496 # If the code compiles ok, we should handle it normally
2447 2497 return self.handle_normal(line_info)
2448 2498
2449 2499 def getapi(self):
2450 2500 """ Get an IPApi object for this shell instance
2451 2501
2452 2502 Getting an IPApi object is always preferable to accessing the shell
2453 2503 directly, but this holds true especially for extensions.
2454 2504
2455 2505 It should always be possible to implement an extension with IPApi
2456 2506 alone. If not, contact maintainer to request an addition.
2457 2507
2458 2508 """
2459 2509 return self.api
2460 2510
2461 2511 def handle_emacs(self, line_info):
2462 2512 """Handle input lines marked by python-mode."""
2463 2513
2464 2514 # Currently, nothing is done. Later more functionality can be added
2465 2515 # here if needed.
2466 2516
2467 2517 # The input cache shouldn't be updated
2468 2518 return line_info.line
2469 2519
2470 2520
2471 2521 def mktempfile(self,data=None):
2472 2522 """Make a new tempfile and return its filename.
2473 2523
2474 2524 This makes a call to tempfile.mktemp, but it registers the created
2475 2525 filename internally so ipython cleans it up at exit time.
2476 2526
2477 2527 Optional inputs:
2478 2528
2479 2529 - data(None): if data is given, it gets written out to the temp file
2480 2530 immediately, and the file is closed again."""
2481 2531
2482 2532 filename = tempfile.mktemp('.py','ipython_edit_')
2483 2533 self.tempfiles.append(filename)
2484 2534
2485 2535 if data:
2486 2536 tmp_file = open(filename,'w')
2487 2537 tmp_file.write(data)
2488 2538 tmp_file.close()
2489 2539 return filename
2490 2540
2491 2541 def write(self,data):
2492 2542 """Write a string to the default output"""
2493 2543 Term.cout.write(data)
2494 2544
2495 2545 def write_err(self,data):
2496 2546 """Write a string to the default error output"""
2497 2547 Term.cerr.write(data)
2498 2548
2499 2549 def ask_exit(self):
2500 2550 """ Call for exiting. Can be overiden and used as a callback. """
2501 2551 self.exit_now = True
2502 2552
2503 2553 def exit(self):
2504 2554 """Handle interactive exit.
2505 2555
2506 2556 This method calls the ask_exit callback."""
2507 2557
2508 2558 if self.rc.confirm_exit:
2509 2559 if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'):
2510 2560 self.ask_exit()
2511 2561 else:
2512 2562 self.ask_exit()
2513 2563
2514 2564 def safe_execfile(self,fname,*where,**kw):
2515 2565 """A safe version of the builtin execfile().
2516 2566
2517 2567 This version will never throw an exception, and knows how to handle
2518 2568 ipython logs as well.
2519 2569
2520 2570 :Parameters:
2521 2571 fname : string
2522 2572 Name of the file to be executed.
2523 2573
2524 2574 where : tuple
2525 2575 One or two namespaces, passed to execfile() as (globals,locals).
2526 2576 If only one is given, it is passed as both.
2527 2577
2528 2578 :Keywords:
2529 2579 islog : boolean (False)
2530 2580
2531 2581 quiet : boolean (True)
2532 2582
2533 2583 exit_ignore : boolean (False)
2534 2584 """
2535 2585
2536 2586 def syspath_cleanup():
2537 2587 """Internal cleanup routine for sys.path."""
2538 2588 if add_dname:
2539 2589 try:
2540 2590 sys.path.remove(dname)
2541 2591 except ValueError:
2542 2592 # For some reason the user has already removed it, ignore.
2543 2593 pass
2544 2594
2545 2595 fname = os.path.expanduser(fname)
2546 2596
2547 2597 # Find things also in current directory. This is needed to mimic the
2548 2598 # behavior of running a script from the system command line, where
2549 2599 # Python inserts the script's directory into sys.path
2550 2600 dname = os.path.dirname(os.path.abspath(fname))
2551 2601 add_dname = False
2552 2602 if dname not in sys.path:
2553 2603 sys.path.insert(0,dname)
2554 2604 add_dname = True
2555 2605
2556 2606 try:
2557 2607 xfile = open(fname)
2558 2608 except:
2559 2609 print >> Term.cerr, \
2560 2610 'Could not open file <%s> for safe execution.' % fname
2561 2611 syspath_cleanup()
2562 2612 return None
2563 2613
2564 2614 kw.setdefault('islog',0)
2565 2615 kw.setdefault('quiet',1)
2566 2616 kw.setdefault('exit_ignore',0)
2567 2617
2568 2618 first = xfile.readline()
2569 2619 loghead = str(self.loghead_tpl).split('\n',1)[0].strip()
2570 2620 xfile.close()
2571 2621 # line by line execution
2572 2622 if first.startswith(loghead) or kw['islog']:
2573 2623 print 'Loading log file <%s> one line at a time...' % fname
2574 2624 if kw['quiet']:
2575 2625 stdout_save = sys.stdout
2576 2626 sys.stdout = StringIO.StringIO()
2577 2627 try:
2578 2628 globs,locs = where[0:2]
2579 2629 except:
2580 2630 try:
2581 2631 globs = locs = where[0]
2582 2632 except:
2583 2633 globs = locs = globals()
2584 2634 badblocks = []
2585 2635
2586 2636 # we also need to identify indented blocks of code when replaying
2587 2637 # logs and put them together before passing them to an exec
2588 2638 # statement. This takes a bit of regexp and look-ahead work in the
2589 2639 # file. It's easiest if we swallow the whole thing in memory
2590 2640 # first, and manually walk through the lines list moving the
2591 2641 # counter ourselves.
2592 2642 indent_re = re.compile('\s+\S')
2593 2643 xfile = open(fname)
2594 2644 filelines = xfile.readlines()
2595 2645 xfile.close()
2596 2646 nlines = len(filelines)
2597 2647 lnum = 0
2598 2648 while lnum < nlines:
2599 2649 line = filelines[lnum]
2600 2650 lnum += 1
2601 2651 # don't re-insert logger status info into cache
2602 2652 if line.startswith('#log#'):
2603 2653 continue
2604 2654 else:
2605 2655 # build a block of code (maybe a single line) for execution
2606 2656 block = line
2607 2657 try:
2608 2658 next = filelines[lnum] # lnum has already incremented
2609 2659 except:
2610 2660 next = None
2611 2661 while next and indent_re.match(next):
2612 2662 block += next
2613 2663 lnum += 1
2614 2664 try:
2615 2665 next = filelines[lnum]
2616 2666 except:
2617 2667 next = None
2618 2668 # now execute the block of one or more lines
2619 2669 try:
2620 2670 exec block in globs,locs
2621 2671 except SystemExit:
2622 2672 pass
2623 2673 except:
2624 2674 badblocks.append(block.rstrip())
2625 2675 if kw['quiet']: # restore stdout
2626 2676 sys.stdout.close()
2627 2677 sys.stdout = stdout_save
2628 2678 print 'Finished replaying log file <%s>' % fname
2629 2679 if badblocks:
2630 2680 print >> sys.stderr, ('\nThe following lines/blocks in file '
2631 2681 '<%s> reported errors:' % fname)
2632 2682
2633 2683 for badline in badblocks:
2634 2684 print >> sys.stderr, badline
2635 2685 else: # regular file execution
2636 2686 try:
2637 2687 if sys.platform == 'win32' and sys.version_info < (2,5,1):
2638 2688 # Work around a bug in Python for Windows. The bug was
2639 2689 # fixed in in Python 2.5 r54159 and 54158, but that's still
2640 2690 # SVN Python as of March/07. For details, see:
2641 2691 # http://projects.scipy.org/ipython/ipython/ticket/123
2642 2692 try:
2643 2693 globs,locs = where[0:2]
2644 2694 except:
2645 2695 try:
2646 2696 globs = locs = where[0]
2647 2697 except:
2648 2698 globs = locs = globals()
2649 2699 exec file(fname) in globs,locs
2650 2700 else:
2651 2701 execfile(fname,*where)
2652 2702 except SyntaxError:
2653 2703 self.showsyntaxerror()
2654 2704 warn('Failure executing file: <%s>' % fname)
2655 2705 except SystemExit,status:
2656 2706 # Code that correctly sets the exit status flag to success (0)
2657 2707 # shouldn't be bothered with a traceback. Note that a plain
2658 2708 # sys.exit() does NOT set the message to 0 (it's empty) so that
2659 2709 # will still get a traceback. Note that the structure of the
2660 2710 # SystemExit exception changed between Python 2.4 and 2.5, so
2661 2711 # the checks must be done in a version-dependent way.
2662 2712 show = False
2663 2713
2664 2714 if sys.version_info[:2] > (2,5):
2665 2715 if status.message!=0 and not kw['exit_ignore']:
2666 2716 show = True
2667 2717 else:
2668 2718 if status.code and not kw['exit_ignore']:
2669 2719 show = True
2670 2720 if show:
2671 2721 self.showtraceback()
2672 2722 warn('Failure executing file: <%s>' % fname)
2673 2723 except:
2674 2724 self.showtraceback()
2675 2725 warn('Failure executing file: <%s>' % fname)
2676 2726
2677 2727 syspath_cleanup()
2678 2728
2679 2729 #************************* end of file <iplib.py> *****************************
@@ -1,6 +1,26 b''
1 1 """Simple script to instantiate a class for testing %run"""
2 2
3 import sys
4
5 # An external test will check that calls to f() work after %run
3 6 class foo: pass
4 7
5 8 def f():
6 foo()
9 return foo()
10
11 # We also want to ensure that while objects remain available for immediate
12 # access, objects from *previous* runs of the same script get collected, to
13 # avoid accumulating massive amounts of old references.
14 class C(object):
15 def __init__(self,name):
16 self.name = name
17
18 def __del__(self):
19 print 'Deleting object:',self.name
20
21 try:
22 name = sys.argv[1]
23 except IndexError:
24 pass
25 else:
26 c = C(name)
@@ -1,115 +1,127 b''
1 1 """Tests for various magic functions.
2 2
3 3 Needs to be run by nose (to make ipython session available).
4 4 """
5 5
6 6 # Standard library imports
7 7 import os
8 8 import sys
9 9
10 10 # Third-party imports
11 11 import nose.tools as nt
12 12
13 13 # From our own code
14 14 from IPython.testing import decorators as dec
15 15
16 16 #-----------------------------------------------------------------------------
17 17 # Test functions begin
18 18
19 19 def test_rehashx():
20 20 # clear up everything
21 21 _ip.IP.alias_table.clear()
22 22 del _ip.db['syscmdlist']
23 23
24 24 _ip.magic('rehashx')
25 25 # Practically ALL ipython development systems will have more than 10 aliases
26 26
27 27 assert len(_ip.IP.alias_table) > 10
28 28 for key, val in _ip.IP.alias_table.items():
29 29 # we must strip dots from alias names
30 30 assert '.' not in key
31 31
32 32 # rehashx must fill up syscmdlist
33 33 scoms = _ip.db['syscmdlist']
34 34 assert len(scoms) > 10
35 35
36 36
37 37 def doctest_run_ns():
38 38 """Classes declared %run scripts must be instantiable afterwards.
39 39
40 In [11]: run tclass
41
42 In [12]: isinstance(f(),foo)
43 Out[12]: True
44 """
45
46
47 def doctest_run_ns2():
48 """Classes declared %run scripts must be instantiable afterwards.
49
40 50 In [3]: run tclass.py
41 51
42 In [4]: f()
52 In [4]: run tclass first_pass
53
54 In [5]: run tclass second_pass
55 Deleting object: first_pass
43 56 """
44 pass # doctest only
45 57
46 58
47 59 def doctest_hist_f():
48 60 """Test %hist -f with temporary filename.
49 61
50 62 In [9]: import tempfile
51 63
52 64 In [10]: tfile = tempfile.mktemp('.py','tmp-ipython-')
53 65
54 66 In [11]: %history -n -f $tfile 3
55 67 """
56 68
57 69
58 70 def doctest_hist_r():
59 71 """Test %hist -r
60 72
61 73 XXX - This test is not recording the output correctly. Not sure why...
62 74
63 75 In [6]: x=1
64 76
65 77 In [7]: hist -n -r 2
66 78 x=1 # random
67 79 hist -n -r 2 # random
68 80 """
69 81
70 82
71 83 def test_shist():
72 84 # Simple tests of ShadowHist class - test generator.
73 85 import os, shutil, tempfile
74 86
75 87 from IPython.Extensions import pickleshare
76 88 from IPython.history import ShadowHist
77 89
78 90 tfile = tempfile.mktemp('','tmp-ipython-')
79 91
80 92 db = pickleshare.PickleShareDB(tfile)
81 93 s = ShadowHist(db)
82 94 s.add('hello')
83 95 s.add('world')
84 96 s.add('hello')
85 97 s.add('hello')
86 98 s.add('karhu')
87 99
88 100 yield nt.assert_equals,s.all(),[(1, 'hello'), (2, 'world'), (3, 'karhu')]
89 101
90 102 yield nt.assert_equal,s.get(2),'world'
91 103
92 104 shutil.rmtree(tfile)
93 105
94 106 @dec.skipif_not_numpy
95 107 def test_numpy_clear_array_undec():
96 108 _ip.ex('import numpy as np')
97 109 _ip.ex('a = np.empty(2)')
98 110
99 111 yield nt.assert_true,'a' in _ip.user_ns
100 112 _ip.magic('clear array')
101 113 yield nt.assert_false,'a' in _ip.user_ns
102 114
103 115
104 116 @dec.skip()
105 117 def test_fail_dec(*a,**k):
106 118 yield nt.assert_true, False
107 119
108 120 @dec.skip('This one shouldn not run')
109 121 def test_fail_dec2(*a,**k):
110 122 yield nt.assert_true, False
111 123
112 124 @dec.skipknownfailure
113 125 def test_fail_dec3(*a,**k):
114 126 yield nt.assert_true, False
115 127
General Comments 0
You need to be logged in to leave comments. Login now