##// END OF EJS Templates
Implement %doctest_mode magic in zmqshell with payload....
Fernando Perez -
Show More
@@ -1,3482 +1,3486 b''
1 1 # encoding: utf-8
2 2 """Magic functions for InteractiveShell.
3 3 """
4 4
5 5 #-----------------------------------------------------------------------------
6 6 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
7 7 # Copyright (C) 2001-2007 Fernando Perez <fperez@colorado.edu>
8 8 # Copyright (C) 2008-2009 The IPython Development Team
9 9
10 10 # Distributed under the terms of the BSD License. The full license is in
11 11 # the file COPYING, distributed as part of this software.
12 12 #-----------------------------------------------------------------------------
13 13
14 14 #-----------------------------------------------------------------------------
15 15 # Imports
16 16 #-----------------------------------------------------------------------------
17 17
18 18 import __builtin__
19 19 import __future__
20 20 import bdb
21 21 import inspect
22 22 import os
23 23 import sys
24 24 import shutil
25 25 import re
26 26 import time
27 27 import textwrap
28 28 import types
29 29 from cStringIO import StringIO
30 30 from getopt import getopt,GetoptError
31 31 from pprint import pformat
32 32
33 33 # cProfile was added in Python2.5
34 34 try:
35 35 import cProfile as profile
36 36 import pstats
37 37 except ImportError:
38 38 # profile isn't bundled by default in Debian for license reasons
39 39 try:
40 40 import profile,pstats
41 41 except ImportError:
42 42 profile = pstats = None
43 43
44 44 # print_function was added to __future__ in Python2.6, remove this when we drop
45 45 # 2.5 compatibility
46 46 if not hasattr(__future__,'CO_FUTURE_PRINT_FUNCTION'):
47 47 __future__.CO_FUTURE_PRINT_FUNCTION = 65536
48 48
49 49 import IPython
50 50 from IPython.core import debugger, oinspect
51 51 from IPython.core.error import TryNext
52 52 from IPython.core.error import UsageError
53 53 from IPython.core.fakemodule import FakeModule
54 54 from IPython.core.macro import Macro
55 55 from IPython.core import page
56 56 from IPython.core.prefilter import ESC_MAGIC
57 57 from IPython.lib.pylabtools import mpl_runner
58 58 from IPython.external.Itpl import itpl, printpl
59 59 from IPython.testing import decorators as testdec
60 60 from IPython.utils.io import file_read, nlprint
61 61 import IPython.utils.io
62 62 from IPython.utils.path import get_py_filename
63 63 from IPython.utils.process import arg_split, abbrev_cwd
64 64 from IPython.utils.terminal import set_term_title
65 65 from IPython.utils.text import LSString, SList, StringTypes, format_screen
66 66 from IPython.utils.timing import clock, clock2
67 67 from IPython.utils.warn import warn, error
68 68 from IPython.utils.ipstruct import Struct
69 69 import IPython.utils.generics
70 70
71 71 #-----------------------------------------------------------------------------
72 72 # Utility functions
73 73 #-----------------------------------------------------------------------------
74 74
75 75 def on_off(tag):
76 76 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
77 77 return ['OFF','ON'][tag]
78 78
79 79 class Bunch: pass
80 80
81 81 def compress_dhist(dh):
82 82 head, tail = dh[:-10], dh[-10:]
83 83
84 84 newhead = []
85 85 done = set()
86 86 for h in head:
87 87 if h in done:
88 88 continue
89 89 newhead.append(h)
90 90 done.add(h)
91 91
92 92 return newhead + tail
93 93
94 94
95 95 #***************************************************************************
96 96 # Main class implementing Magic functionality
97 97
98 98 # XXX - for some odd reason, if Magic is made a new-style class, we get errors
99 99 # on construction of the main InteractiveShell object. Something odd is going
100 100 # on with super() calls, Configurable and the MRO... For now leave it as-is, but
101 101 # eventually this needs to be clarified.
102 102 # BG: This is because InteractiveShell inherits from this, but is itself a
103 103 # Configurable. This messes up the MRO in some way. The fix is that we need to
104 104 # make Magic a configurable that InteractiveShell does not subclass.
105 105
106 106 class Magic:
107 107 """Magic functions for InteractiveShell.
108 108
109 109 Shell functions which can be reached as %function_name. All magic
110 110 functions should accept a string, which they can parse for their own
111 111 needs. This can make some functions easier to type, eg `%cd ../`
112 112 vs. `%cd("../")`
113 113
114 114 ALL definitions MUST begin with the prefix magic_. The user won't need it
115 115 at the command line, but it is is needed in the definition. """
116 116
117 117 # class globals
118 118 auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.',
119 119 'Automagic is ON, % prefix NOT needed for magic functions.']
120 120
121 121 #......................................................................
122 122 # some utility functions
123 123
124 124 def __init__(self,shell):
125 125
126 126 self.options_table = {}
127 127 if profile is None:
128 128 self.magic_prun = self.profile_missing_notice
129 129 self.shell = shell
130 130
131 131 # namespace for holding state we may need
132 132 self._magic_state = Bunch()
133 133
134 134 def profile_missing_notice(self, *args, **kwargs):
135 135 error("""\
136 136 The profile module could not be found. It has been removed from the standard
137 137 python packages because of its non-free license. To use profiling, install the
138 138 python-profiler package from non-free.""")
139 139
140 140 def default_option(self,fn,optstr):
141 141 """Make an entry in the options_table for fn, with value optstr"""
142 142
143 143 if fn not in self.lsmagic():
144 144 error("%s is not a magic function" % fn)
145 145 self.options_table[fn] = optstr
146 146
147 147 def lsmagic(self):
148 148 """Return a list of currently available magic functions.
149 149
150 150 Gives a list of the bare names after mangling (['ls','cd', ...], not
151 151 ['magic_ls','magic_cd',...]"""
152 152
153 153 # FIXME. This needs a cleanup, in the way the magics list is built.
154 154
155 155 # magics in class definition
156 156 class_magic = lambda fn: fn.startswith('magic_') and \
157 157 callable(Magic.__dict__[fn])
158 158 # in instance namespace (run-time user additions)
159 159 inst_magic = lambda fn: fn.startswith('magic_') and \
160 160 callable(self.__dict__[fn])
161 161 # and bound magics by user (so they can access self):
162 162 inst_bound_magic = lambda fn: fn.startswith('magic_') and \
163 163 callable(self.__class__.__dict__[fn])
164 164 magics = filter(class_magic,Magic.__dict__.keys()) + \
165 165 filter(inst_magic,self.__dict__.keys()) + \
166 166 filter(inst_bound_magic,self.__class__.__dict__.keys())
167 167 out = []
168 168 for fn in set(magics):
169 169 out.append(fn.replace('magic_','',1))
170 170 out.sort()
171 171 return out
172 172
173 173 def extract_input_slices(self,slices,raw=False):
174 174 """Return as a string a set of input history slices.
175 175
176 176 Inputs:
177 177
178 178 - slices: the set of slices is given as a list of strings (like
179 179 ['1','4:8','9'], since this function is for use by magic functions
180 180 which get their arguments as strings.
181 181
182 182 Optional inputs:
183 183
184 184 - raw(False): by default, the processed input is used. If this is
185 185 true, the raw input history is used instead.
186 186
187 187 Note that slices can be called with two notations:
188 188
189 189 N:M -> standard python form, means including items N...(M-1).
190 190
191 191 N-M -> include items N..M (closed endpoint)."""
192 192
193 193 if raw:
194 194 hist = self.shell.input_hist_raw
195 195 else:
196 196 hist = self.shell.input_hist
197 197
198 198 cmds = []
199 199 for chunk in slices:
200 200 if ':' in chunk:
201 201 ini,fin = map(int,chunk.split(':'))
202 202 elif '-' in chunk:
203 203 ini,fin = map(int,chunk.split('-'))
204 204 fin += 1
205 205 else:
206 206 ini = int(chunk)
207 207 fin = ini+1
208 208 cmds.append(hist[ini:fin])
209 209 return cmds
210 210
211 211 def arg_err(self,func):
212 212 """Print docstring if incorrect arguments were passed"""
213 213 print 'Error in arguments:'
214 214 print oinspect.getdoc(func)
215 215
216 216 def format_latex(self,strng):
217 217 """Format a string for latex inclusion."""
218 218
219 219 # Characters that need to be escaped for latex:
220 220 escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE)
221 221 # Magic command names as headers:
222 222 cmd_name_re = re.compile(r'^(%s.*?):' % ESC_MAGIC,
223 223 re.MULTILINE)
224 224 # Magic commands
225 225 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % ESC_MAGIC,
226 226 re.MULTILINE)
227 227 # Paragraph continue
228 228 par_re = re.compile(r'\\$',re.MULTILINE)
229 229
230 230 # The "\n" symbol
231 231 newline_re = re.compile(r'\\n')
232 232
233 233 # Now build the string for output:
234 234 #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
235 235 strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
236 236 strng)
237 237 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
238 238 strng = par_re.sub(r'\\\\',strng)
239 239 strng = escape_re.sub(r'\\\1',strng)
240 240 strng = newline_re.sub(r'\\textbackslash{}n',strng)
241 241 return strng
242 242
243 243 def parse_options(self,arg_str,opt_str,*long_opts,**kw):
244 244 """Parse options passed to an argument string.
245 245
246 246 The interface is similar to that of getopt(), but it returns back a
247 247 Struct with the options as keys and the stripped argument string still
248 248 as a string.
249 249
250 250 arg_str is quoted as a true sys.argv vector by using shlex.split.
251 251 This allows us to easily expand variables, glob files, quote
252 252 arguments, etc.
253 253
254 254 Options:
255 255 -mode: default 'string'. If given as 'list', the argument string is
256 256 returned as a list (split on whitespace) instead of a string.
257 257
258 258 -list_all: put all option values in lists. Normally only options
259 259 appearing more than once are put in a list.
260 260
261 261 -posix (True): whether to split the input line in POSIX mode or not,
262 262 as per the conventions outlined in the shlex module from the
263 263 standard library."""
264 264
265 265 # inject default options at the beginning of the input line
266 266 caller = sys._getframe(1).f_code.co_name.replace('magic_','')
267 267 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
268 268
269 269 mode = kw.get('mode','string')
270 270 if mode not in ['string','list']:
271 271 raise ValueError,'incorrect mode given: %s' % mode
272 272 # Get options
273 273 list_all = kw.get('list_all',0)
274 274 posix = kw.get('posix', os.name == 'posix')
275 275
276 276 # Check if we have more than one argument to warrant extra processing:
277 277 odict = {} # Dictionary with options
278 278 args = arg_str.split()
279 279 if len(args) >= 1:
280 280 # If the list of inputs only has 0 or 1 thing in it, there's no
281 281 # need to look for options
282 282 argv = arg_split(arg_str,posix)
283 283 # Do regular option processing
284 284 try:
285 285 opts,args = getopt(argv,opt_str,*long_opts)
286 286 except GetoptError,e:
287 287 raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str,
288 288 " ".join(long_opts)))
289 289 for o,a in opts:
290 290 if o.startswith('--'):
291 291 o = o[2:]
292 292 else:
293 293 o = o[1:]
294 294 try:
295 295 odict[o].append(a)
296 296 except AttributeError:
297 297 odict[o] = [odict[o],a]
298 298 except KeyError:
299 299 if list_all:
300 300 odict[o] = [a]
301 301 else:
302 302 odict[o] = a
303 303
304 304 # Prepare opts,args for return
305 305 opts = Struct(odict)
306 306 if mode == 'string':
307 307 args = ' '.join(args)
308 308
309 309 return opts,args
310 310
311 311 #......................................................................
312 312 # And now the actual magic functions
313 313
314 314 # Functions for IPython shell work (vars,funcs, config, etc)
315 315 def magic_lsmagic(self, parameter_s = ''):
316 316 """List currently available magic functions."""
317 317 mesc = ESC_MAGIC
318 318 print 'Available magic functions:\n'+mesc+\
319 319 (' '+mesc).join(self.lsmagic())
320 320 print '\n' + Magic.auto_status[self.shell.automagic]
321 321 return None
322 322
323 323 def magic_magic(self, parameter_s = ''):
324 324 """Print information about the magic function system.
325 325
326 326 Supported formats: -latex, -brief, -rest
327 327 """
328 328
329 329 mode = ''
330 330 try:
331 331 if parameter_s.split()[0] == '-latex':
332 332 mode = 'latex'
333 333 if parameter_s.split()[0] == '-brief':
334 334 mode = 'brief'
335 335 if parameter_s.split()[0] == '-rest':
336 336 mode = 'rest'
337 337 rest_docs = []
338 338 except:
339 339 pass
340 340
341 341 magic_docs = []
342 342 for fname in self.lsmagic():
343 343 mname = 'magic_' + fname
344 344 for space in (Magic,self,self.__class__):
345 345 try:
346 346 fn = space.__dict__[mname]
347 347 except KeyError:
348 348 pass
349 349 else:
350 350 break
351 351 if mode == 'brief':
352 352 # only first line
353 353 if fn.__doc__:
354 354 fndoc = fn.__doc__.split('\n',1)[0]
355 355 else:
356 356 fndoc = 'No documentation'
357 357 else:
358 358 if fn.__doc__:
359 359 fndoc = fn.__doc__.rstrip()
360 360 else:
361 361 fndoc = 'No documentation'
362 362
363 363
364 364 if mode == 'rest':
365 365 rest_docs.append('**%s%s**::\n\n\t%s\n\n' %(ESC_MAGIC,
366 366 fname,fndoc))
367 367
368 368 else:
369 369 magic_docs.append('%s%s:\n\t%s\n' %(ESC_MAGIC,
370 370 fname,fndoc))
371 371
372 372 magic_docs = ''.join(magic_docs)
373 373
374 374 if mode == 'rest':
375 375 return "".join(rest_docs)
376 376
377 377 if mode == 'latex':
378 378 print self.format_latex(magic_docs)
379 379 return
380 380 else:
381 381 magic_docs = format_screen(magic_docs)
382 382 if mode == 'brief':
383 383 return magic_docs
384 384
385 385 outmsg = """
386 386 IPython's 'magic' functions
387 387 ===========================
388 388
389 389 The magic function system provides a series of functions which allow you to
390 390 control the behavior of IPython itself, plus a lot of system-type
391 391 features. All these functions are prefixed with a % character, but parameters
392 392 are given without parentheses or quotes.
393 393
394 394 NOTE: If you have 'automagic' enabled (via the command line option or with the
395 395 %automagic function), you don't need to type in the % explicitly. By default,
396 396 IPython ships with automagic on, so you should only rarely need the % escape.
397 397
398 398 Example: typing '%cd mydir' (without the quotes) changes you working directory
399 399 to 'mydir', if it exists.
400 400
401 401 You can define your own magic functions to extend the system. See the supplied
402 402 ipythonrc and example-magic.py files for details (in your ipython
403 403 configuration directory, typically $HOME/.ipython/).
404 404
405 405 You can also define your own aliased names for magic functions. In your
406 406 ipythonrc file, placing a line like:
407 407
408 408 execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
409 409
410 410 will define %pf as a new name for %profile.
411 411
412 412 You can also call magics in code using the magic() function, which IPython
413 413 automatically adds to the builtin namespace. Type 'magic?' for details.
414 414
415 415 For a list of the available magic functions, use %lsmagic. For a description
416 416 of any of them, type %magic_name?, e.g. '%cd?'.
417 417
418 418 Currently the magic system has the following functions:\n"""
419 419
420 420 mesc = ESC_MAGIC
421 421 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
422 422 "\n\n%s%s\n\n%s" % (outmsg,
423 423 magic_docs,mesc,mesc,
424 424 (' '+mesc).join(self.lsmagic()),
425 425 Magic.auto_status[self.shell.automagic] ) )
426 426 page.page(outmsg)
427 427
428 428 def magic_autoindent(self, parameter_s = ''):
429 429 """Toggle autoindent on/off (if available)."""
430 430
431 431 self.shell.set_autoindent()
432 432 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
433 433
434 434 def magic_automagic(self, parameter_s = ''):
435 435 """Make magic functions callable without having to type the initial %.
436 436
437 437 Without argumentsl toggles on/off (when off, you must call it as
438 438 %automagic, of course). With arguments it sets the value, and you can
439 439 use any of (case insensitive):
440 440
441 441 - on,1,True: to activate
442 442
443 443 - off,0,False: to deactivate.
444 444
445 445 Note that magic functions have lowest priority, so if there's a
446 446 variable whose name collides with that of a magic fn, automagic won't
447 447 work for that function (you get the variable instead). However, if you
448 448 delete the variable (del var), the previously shadowed magic function
449 449 becomes visible to automagic again."""
450 450
451 451 arg = parameter_s.lower()
452 452 if parameter_s in ('on','1','true'):
453 453 self.shell.automagic = True
454 454 elif parameter_s in ('off','0','false'):
455 455 self.shell.automagic = False
456 456 else:
457 457 self.shell.automagic = not self.shell.automagic
458 458 print '\n' + Magic.auto_status[self.shell.automagic]
459 459
460 460 @testdec.skip_doctest
461 461 def magic_autocall(self, parameter_s = ''):
462 462 """Make functions callable without having to type parentheses.
463 463
464 464 Usage:
465 465
466 466 %autocall [mode]
467 467
468 468 The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the
469 469 value is toggled on and off (remembering the previous state).
470 470
471 471 In more detail, these values mean:
472 472
473 473 0 -> fully disabled
474 474
475 475 1 -> active, but do not apply if there are no arguments on the line.
476 476
477 477 In this mode, you get:
478 478
479 479 In [1]: callable
480 480 Out[1]: <built-in function callable>
481 481
482 482 In [2]: callable 'hello'
483 483 ------> callable('hello')
484 484 Out[2]: False
485 485
486 486 2 -> Active always. Even if no arguments are present, the callable
487 487 object is called:
488 488
489 489 In [2]: float
490 490 ------> float()
491 491 Out[2]: 0.0
492 492
493 493 Note that even with autocall off, you can still use '/' at the start of
494 494 a line to treat the first argument on the command line as a function
495 495 and add parentheses to it:
496 496
497 497 In [8]: /str 43
498 498 ------> str(43)
499 499 Out[8]: '43'
500 500
501 501 # all-random (note for auto-testing)
502 502 """
503 503
504 504 if parameter_s:
505 505 arg = int(parameter_s)
506 506 else:
507 507 arg = 'toggle'
508 508
509 509 if not arg in (0,1,2,'toggle'):
510 510 error('Valid modes: (0->Off, 1->Smart, 2->Full')
511 511 return
512 512
513 513 if arg in (0,1,2):
514 514 self.shell.autocall = arg
515 515 else: # toggle
516 516 if self.shell.autocall:
517 517 self._magic_state.autocall_save = self.shell.autocall
518 518 self.shell.autocall = 0
519 519 else:
520 520 try:
521 521 self.shell.autocall = self._magic_state.autocall_save
522 522 except AttributeError:
523 523 self.shell.autocall = self._magic_state.autocall_save = 1
524 524
525 525 print "Automatic calling is:",['OFF','Smart','Full'][self.shell.autocall]
526 526
527 527
528 528 def magic_page(self, parameter_s=''):
529 529 """Pretty print the object and display it through a pager.
530 530
531 531 %page [options] OBJECT
532 532
533 533 If no object is given, use _ (last output).
534 534
535 535 Options:
536 536
537 537 -r: page str(object), don't pretty-print it."""
538 538
539 539 # After a function contributed by Olivier Aubert, slightly modified.
540 540
541 541 # Process options/args
542 542 opts,args = self.parse_options(parameter_s,'r')
543 543 raw = 'r' in opts
544 544
545 545 oname = args and args or '_'
546 546 info = self._ofind(oname)
547 547 if info['found']:
548 548 txt = (raw and str or pformat)( info['obj'] )
549 549 page.page(txt)
550 550 else:
551 551 print 'Object `%s` not found' % oname
552 552
553 553 def magic_profile(self, parameter_s=''):
554 554 """Print your currently active IPython profile."""
555 555 if self.shell.profile:
556 556 printpl('Current IPython profile: $self.shell.profile.')
557 557 else:
558 558 print 'No profile active.'
559 559
560 560 def magic_pinfo(self, parameter_s='', namespaces=None):
561 561 """Provide detailed information about an object.
562 562
563 563 '%pinfo object' is just a synonym for object? or ?object."""
564 564
565 565 #print 'pinfo par: <%s>' % parameter_s # dbg
566 566
567 567
568 568 # detail_level: 0 -> obj? , 1 -> obj??
569 569 detail_level = 0
570 570 # We need to detect if we got called as 'pinfo pinfo foo', which can
571 571 # happen if the user types 'pinfo foo?' at the cmd line.
572 572 pinfo,qmark1,oname,qmark2 = \
573 573 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
574 574 if pinfo or qmark1 or qmark2:
575 575 detail_level = 1
576 576 if "*" in oname:
577 577 self.magic_psearch(oname)
578 578 else:
579 579 self.shell._inspect('pinfo', oname, detail_level=detail_level,
580 580 namespaces=namespaces)
581 581
582 582 def magic_pdef(self, parameter_s='', namespaces=None):
583 583 """Print the definition header for any callable object.
584 584
585 585 If the object is a class, print the constructor information."""
586 586 self._inspect('pdef',parameter_s, namespaces)
587 587
588 588 def magic_pdoc(self, parameter_s='', namespaces=None):
589 589 """Print the docstring for an object.
590 590
591 591 If the given object is a class, it will print both the class and the
592 592 constructor docstrings."""
593 593 self._inspect('pdoc',parameter_s, namespaces)
594 594
595 595 def magic_psource(self, parameter_s='', namespaces=None):
596 596 """Print (or run through pager) the source code for an object."""
597 597 self._inspect('psource',parameter_s, namespaces)
598 598
599 599 def magic_pfile(self, parameter_s=''):
600 600 """Print (or run through pager) the file where an object is defined.
601 601
602 602 The file opens at the line where the object definition begins. IPython
603 603 will honor the environment variable PAGER if set, and otherwise will
604 604 do its best to print the file in a convenient form.
605 605
606 606 If the given argument is not an object currently defined, IPython will
607 607 try to interpret it as a filename (automatically adding a .py extension
608 608 if needed). You can thus use %pfile as a syntax highlighting code
609 609 viewer."""
610 610
611 611 # first interpret argument as an object name
612 612 out = self._inspect('pfile',parameter_s)
613 613 # if not, try the input as a filename
614 614 if out == 'not found':
615 615 try:
616 616 filename = get_py_filename(parameter_s)
617 617 except IOError,msg:
618 618 print msg
619 619 return
620 620 page.page(self.shell.inspector.format(file(filename).read()))
621 621
622 622 def magic_psearch(self, parameter_s=''):
623 623 """Search for object in namespaces by wildcard.
624 624
625 625 %psearch [options] PATTERN [OBJECT TYPE]
626 626
627 627 Note: ? can be used as a synonym for %psearch, at the beginning or at
628 628 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
629 629 rest of the command line must be unchanged (options come first), so
630 630 for example the following forms are equivalent
631 631
632 632 %psearch -i a* function
633 633 -i a* function?
634 634 ?-i a* function
635 635
636 636 Arguments:
637 637
638 638 PATTERN
639 639
640 640 where PATTERN is a string containing * as a wildcard similar to its
641 641 use in a shell. The pattern is matched in all namespaces on the
642 642 search path. By default objects starting with a single _ are not
643 643 matched, many IPython generated objects have a single
644 644 underscore. The default is case insensitive matching. Matching is
645 645 also done on the attributes of objects and not only on the objects
646 646 in a module.
647 647
648 648 [OBJECT TYPE]
649 649
650 650 Is the name of a python type from the types module. The name is
651 651 given in lowercase without the ending type, ex. StringType is
652 652 written string. By adding a type here only objects matching the
653 653 given type are matched. Using all here makes the pattern match all
654 654 types (this is the default).
655 655
656 656 Options:
657 657
658 658 -a: makes the pattern match even objects whose names start with a
659 659 single underscore. These names are normally ommitted from the
660 660 search.
661 661
662 662 -i/-c: make the pattern case insensitive/sensitive. If neither of
663 663 these options is given, the default is read from your ipythonrc
664 664 file. The option name which sets this value is
665 665 'wildcards_case_sensitive'. If this option is not specified in your
666 666 ipythonrc file, IPython's internal default is to do a case sensitive
667 667 search.
668 668
669 669 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
670 670 specifiy can be searched in any of the following namespaces:
671 671 'builtin', 'user', 'user_global','internal', 'alias', where
672 672 'builtin' and 'user' are the search defaults. Note that you should
673 673 not use quotes when specifying namespaces.
674 674
675 675 'Builtin' contains the python module builtin, 'user' contains all
676 676 user data, 'alias' only contain the shell aliases and no python
677 677 objects, 'internal' contains objects used by IPython. The
678 678 'user_global' namespace is only used by embedded IPython instances,
679 679 and it contains module-level globals. You can add namespaces to the
680 680 search with -s or exclude them with -e (these options can be given
681 681 more than once).
682 682
683 683 Examples:
684 684
685 685 %psearch a* -> objects beginning with an a
686 686 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
687 687 %psearch a* function -> all functions beginning with an a
688 688 %psearch re.e* -> objects beginning with an e in module re
689 689 %psearch r*.e* -> objects that start with e in modules starting in r
690 690 %psearch r*.* string -> all strings in modules beginning with r
691 691
692 692 Case sensitve search:
693 693
694 694 %psearch -c a* list all object beginning with lower case a
695 695
696 696 Show objects beginning with a single _:
697 697
698 698 %psearch -a _* list objects beginning with a single underscore"""
699 699 try:
700 700 parameter_s = parameter_s.encode('ascii')
701 701 except UnicodeEncodeError:
702 702 print 'Python identifiers can only contain ascii characters.'
703 703 return
704 704
705 705 # default namespaces to be searched
706 706 def_search = ['user','builtin']
707 707
708 708 # Process options/args
709 709 opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
710 710 opt = opts.get
711 711 shell = self.shell
712 712 psearch = shell.inspector.psearch
713 713
714 714 # select case options
715 715 if opts.has_key('i'):
716 716 ignore_case = True
717 717 elif opts.has_key('c'):
718 718 ignore_case = False
719 719 else:
720 720 ignore_case = not shell.wildcards_case_sensitive
721 721
722 722 # Build list of namespaces to search from user options
723 723 def_search.extend(opt('s',[]))
724 724 ns_exclude = ns_exclude=opt('e',[])
725 725 ns_search = [nm for nm in def_search if nm not in ns_exclude]
726 726
727 727 # Call the actual search
728 728 try:
729 729 psearch(args,shell.ns_table,ns_search,
730 730 show_all=opt('a'),ignore_case=ignore_case)
731 731 except:
732 732 shell.showtraceback()
733 733
734 734 def magic_who_ls(self, parameter_s=''):
735 735 """Return a sorted list of all interactive variables.
736 736
737 737 If arguments are given, only variables of types matching these
738 738 arguments are returned."""
739 739
740 740 user_ns = self.shell.user_ns
741 741 internal_ns = self.shell.internal_ns
742 742 user_ns_hidden = self.shell.user_ns_hidden
743 743 out = [ i for i in user_ns
744 744 if not i.startswith('_') \
745 745 and not (i in internal_ns or i in user_ns_hidden) ]
746 746
747 747 typelist = parameter_s.split()
748 748 if typelist:
749 749 typeset = set(typelist)
750 750 out = [i for i in out if type(i).__name__ in typeset]
751 751
752 752 out.sort()
753 753 return out
754 754
755 755 def magic_who(self, parameter_s=''):
756 756 """Print all interactive variables, with some minimal formatting.
757 757
758 758 If any arguments are given, only variables whose type matches one of
759 759 these are printed. For example:
760 760
761 761 %who function str
762 762
763 763 will only list functions and strings, excluding all other types of
764 764 variables. To find the proper type names, simply use type(var) at a
765 765 command line to see how python prints type names. For example:
766 766
767 767 In [1]: type('hello')\\
768 768 Out[1]: <type 'str'>
769 769
770 770 indicates that the type name for strings is 'str'.
771 771
772 772 %who always excludes executed names loaded through your configuration
773 773 file and things which are internal to IPython.
774 774
775 775 This is deliberate, as typically you may load many modules and the
776 776 purpose of %who is to show you only what you've manually defined."""
777 777
778 778 varlist = self.magic_who_ls(parameter_s)
779 779 if not varlist:
780 780 if parameter_s:
781 781 print 'No variables match your requested type.'
782 782 else:
783 783 print 'Interactive namespace is empty.'
784 784 return
785 785
786 786 # if we have variables, move on...
787 787 count = 0
788 788 for i in varlist:
789 789 print i+'\t',
790 790 count += 1
791 791 if count > 8:
792 792 count = 0
793 793 print
794 794 print
795 795
796 796 def magic_whos(self, parameter_s=''):
797 797 """Like %who, but gives some extra information about each variable.
798 798
799 799 The same type filtering of %who can be applied here.
800 800
801 801 For all variables, the type is printed. Additionally it prints:
802 802
803 803 - For {},[],(): their length.
804 804
805 805 - For numpy and Numeric arrays, a summary with shape, number of
806 806 elements, typecode and size in memory.
807 807
808 808 - Everything else: a string representation, snipping their middle if
809 809 too long."""
810 810
811 811 varnames = self.magic_who_ls(parameter_s)
812 812 if not varnames:
813 813 if parameter_s:
814 814 print 'No variables match your requested type.'
815 815 else:
816 816 print 'Interactive namespace is empty.'
817 817 return
818 818
819 819 # if we have variables, move on...
820 820
821 821 # for these types, show len() instead of data:
822 822 seq_types = [types.DictType,types.ListType,types.TupleType]
823 823
824 824 # for numpy/Numeric arrays, display summary info
825 825 try:
826 826 import numpy
827 827 except ImportError:
828 828 ndarray_type = None
829 829 else:
830 830 ndarray_type = numpy.ndarray.__name__
831 831 try:
832 832 import Numeric
833 833 except ImportError:
834 834 array_type = None
835 835 else:
836 836 array_type = Numeric.ArrayType.__name__
837 837
838 838 # Find all variable names and types so we can figure out column sizes
839 839 def get_vars(i):
840 840 return self.shell.user_ns[i]
841 841
842 842 # some types are well known and can be shorter
843 843 abbrevs = {'IPython.core.macro.Macro' : 'Macro'}
844 844 def type_name(v):
845 845 tn = type(v).__name__
846 846 return abbrevs.get(tn,tn)
847 847
848 848 varlist = map(get_vars,varnames)
849 849
850 850 typelist = []
851 851 for vv in varlist:
852 852 tt = type_name(vv)
853 853
854 854 if tt=='instance':
855 855 typelist.append( abbrevs.get(str(vv.__class__),
856 856 str(vv.__class__)))
857 857 else:
858 858 typelist.append(tt)
859 859
860 860 # column labels and # of spaces as separator
861 861 varlabel = 'Variable'
862 862 typelabel = 'Type'
863 863 datalabel = 'Data/Info'
864 864 colsep = 3
865 865 # variable format strings
866 866 vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)"
867 867 vfmt_short = '$vstr[:25]<...>$vstr[-25:]'
868 868 aformat = "%s: %s elems, type `%s`, %s bytes"
869 869 # find the size of the columns to format the output nicely
870 870 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
871 871 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
872 872 # table header
873 873 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
874 874 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
875 875 # and the table itself
876 876 kb = 1024
877 877 Mb = 1048576 # kb**2
878 878 for vname,var,vtype in zip(varnames,varlist,typelist):
879 879 print itpl(vformat),
880 880 if vtype in seq_types:
881 881 print len(var)
882 882 elif vtype in [array_type,ndarray_type]:
883 883 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
884 884 if vtype==ndarray_type:
885 885 # numpy
886 886 vsize = var.size
887 887 vbytes = vsize*var.itemsize
888 888 vdtype = var.dtype
889 889 else:
890 890 # Numeric
891 891 vsize = Numeric.size(var)
892 892 vbytes = vsize*var.itemsize()
893 893 vdtype = var.typecode()
894 894
895 895 if vbytes < 100000:
896 896 print aformat % (vshape,vsize,vdtype,vbytes)
897 897 else:
898 898 print aformat % (vshape,vsize,vdtype,vbytes),
899 899 if vbytes < Mb:
900 900 print '(%s kb)' % (vbytes/kb,)
901 901 else:
902 902 print '(%s Mb)' % (vbytes/Mb,)
903 903 else:
904 904 try:
905 905 vstr = str(var)
906 906 except UnicodeEncodeError:
907 907 vstr = unicode(var).encode(sys.getdefaultencoding(),
908 908 'backslashreplace')
909 909 vstr = vstr.replace('\n','\\n')
910 910 if len(vstr) < 50:
911 911 print vstr
912 912 else:
913 913 printpl(vfmt_short)
914 914
915 915 def magic_reset(self, parameter_s=''):
916 916 """Resets the namespace by removing all names defined by the user.
917 917
918 918 Input/Output history are left around in case you need them.
919 919
920 920 Parameters
921 921 ----------
922 922 -y : force reset without asking for confirmation.
923 923
924 924 Examples
925 925 --------
926 926 In [6]: a = 1
927 927
928 928 In [7]: a
929 929 Out[7]: 1
930 930
931 931 In [8]: 'a' in _ip.user_ns
932 932 Out[8]: True
933 933
934 934 In [9]: %reset -f
935 935
936 936 In [10]: 'a' in _ip.user_ns
937 937 Out[10]: False
938 938 """
939 939
940 940 if parameter_s == '-f':
941 941 ans = True
942 942 else:
943 943 ans = self.shell.ask_yes_no(
944 944 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ")
945 945 if not ans:
946 946 print 'Nothing done.'
947 947 return
948 948 user_ns = self.shell.user_ns
949 949 for i in self.magic_who_ls():
950 950 del(user_ns[i])
951 951
952 952 # Also flush the private list of module references kept for script
953 953 # execution protection
954 954 self.shell.clear_main_mod_cache()
955 955
956 956 def magic_reset_selective(self, parameter_s=''):
957 957 """Resets the namespace by removing names defined by the user.
958 958
959 959 Input/Output history are left around in case you need them.
960 960
961 961 %reset_selective [-f] regex
962 962
963 963 No action is taken if regex is not included
964 964
965 965 Options
966 966 -f : force reset without asking for confirmation.
967 967
968 968 Examples
969 969 --------
970 970
971 971 We first fully reset the namespace so your output looks identical to
972 972 this example for pedagogical reasons; in practice you do not need a
973 973 full reset.
974 974
975 975 In [1]: %reset -f
976 976
977 977 Now, with a clean namespace we can make a few variables and use
978 978 %reset_selective to only delete names that match our regexp:
979 979
980 980 In [2]: a=1; b=2; c=3; b1m=4; b2m=5; b3m=6; b4m=7; b2s=8
981 981
982 982 In [3]: who_ls
983 983 Out[3]: ['a', 'b', 'b1m', 'b2m', 'b2s', 'b3m', 'b4m', 'c']
984 984
985 985 In [4]: %reset_selective -f b[2-3]m
986 986
987 987 In [5]: who_ls
988 988 Out[5]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c']
989 989
990 990 In [6]: %reset_selective -f d
991 991
992 992 In [7]: who_ls
993 993 Out[7]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c']
994 994
995 995 In [8]: %reset_selective -f c
996 996
997 997 In [9]: who_ls
998 998 Out[9]: ['a', 'b', 'b1m', 'b2s', 'b4m']
999 999
1000 1000 In [10]: %reset_selective -f b
1001 1001
1002 1002 In [11]: who_ls
1003 1003 Out[11]: ['a']
1004 1004 """
1005 1005
1006 1006 opts, regex = self.parse_options(parameter_s,'f')
1007 1007
1008 1008 if opts.has_key('f'):
1009 1009 ans = True
1010 1010 else:
1011 1011 ans = self.shell.ask_yes_no(
1012 1012 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ")
1013 1013 if not ans:
1014 1014 print 'Nothing done.'
1015 1015 return
1016 1016 user_ns = self.shell.user_ns
1017 1017 if not regex:
1018 1018 print 'No regex pattern specified. Nothing done.'
1019 1019 return
1020 1020 else:
1021 1021 try:
1022 1022 m = re.compile(regex)
1023 1023 except TypeError:
1024 1024 raise TypeError('regex must be a string or compiled pattern')
1025 1025 for i in self.magic_who_ls():
1026 1026 if m.search(i):
1027 1027 del(user_ns[i])
1028 1028
1029 1029 def magic_logstart(self,parameter_s=''):
1030 1030 """Start logging anywhere in a session.
1031 1031
1032 1032 %logstart [-o|-r|-t] [log_name [log_mode]]
1033 1033
1034 1034 If no name is given, it defaults to a file named 'ipython_log.py' in your
1035 1035 current directory, in 'rotate' mode (see below).
1036 1036
1037 1037 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
1038 1038 history up to that point and then continues logging.
1039 1039
1040 1040 %logstart takes a second optional parameter: logging mode. This can be one
1041 1041 of (note that the modes are given unquoted):\\
1042 1042 append: well, that says it.\\
1043 1043 backup: rename (if exists) to name~ and start name.\\
1044 1044 global: single logfile in your home dir, appended to.\\
1045 1045 over : overwrite existing log.\\
1046 1046 rotate: create rotating logs name.1~, name.2~, etc.
1047 1047
1048 1048 Options:
1049 1049
1050 1050 -o: log also IPython's output. In this mode, all commands which
1051 1051 generate an Out[NN] prompt are recorded to the logfile, right after
1052 1052 their corresponding input line. The output lines are always
1053 1053 prepended with a '#[Out]# ' marker, so that the log remains valid
1054 1054 Python code.
1055 1055
1056 1056 Since this marker is always the same, filtering only the output from
1057 1057 a log is very easy, using for example a simple awk call:
1058 1058
1059 1059 awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py
1060 1060
1061 1061 -r: log 'raw' input. Normally, IPython's logs contain the processed
1062 1062 input, so that user lines are logged in their final form, converted
1063 1063 into valid Python. For example, %Exit is logged as
1064 1064 '_ip.magic("Exit"). If the -r flag is given, all input is logged
1065 1065 exactly as typed, with no transformations applied.
1066 1066
1067 1067 -t: put timestamps before each input line logged (these are put in
1068 1068 comments)."""
1069 1069
1070 1070 opts,par = self.parse_options(parameter_s,'ort')
1071 1071 log_output = 'o' in opts
1072 1072 log_raw_input = 'r' in opts
1073 1073 timestamp = 't' in opts
1074 1074
1075 1075 logger = self.shell.logger
1076 1076
1077 1077 # if no args are given, the defaults set in the logger constructor by
1078 1078 # ipytohn remain valid
1079 1079 if par:
1080 1080 try:
1081 1081 logfname,logmode = par.split()
1082 1082 except:
1083 1083 logfname = par
1084 1084 logmode = 'backup'
1085 1085 else:
1086 1086 logfname = logger.logfname
1087 1087 logmode = logger.logmode
1088 1088 # put logfname into rc struct as if it had been called on the command
1089 1089 # line, so it ends up saved in the log header Save it in case we need
1090 1090 # to restore it...
1091 1091 old_logfile = self.shell.logfile
1092 1092 if logfname:
1093 1093 logfname = os.path.expanduser(logfname)
1094 1094 self.shell.logfile = logfname
1095 1095
1096 1096 loghead = '# IPython log file\n\n'
1097 1097 try:
1098 1098 started = logger.logstart(logfname,loghead,logmode,
1099 1099 log_output,timestamp,log_raw_input)
1100 1100 except:
1101 1101 self.shell.logfile = old_logfile
1102 1102 warn("Couldn't start log: %s" % sys.exc_info()[1])
1103 1103 else:
1104 1104 # log input history up to this point, optionally interleaving
1105 1105 # output if requested
1106 1106
1107 1107 if timestamp:
1108 1108 # disable timestamping for the previous history, since we've
1109 1109 # lost those already (no time machine here).
1110 1110 logger.timestamp = False
1111 1111
1112 1112 if log_raw_input:
1113 1113 input_hist = self.shell.input_hist_raw
1114 1114 else:
1115 1115 input_hist = self.shell.input_hist
1116 1116
1117 1117 if log_output:
1118 1118 log_write = logger.log_write
1119 1119 output_hist = self.shell.output_hist
1120 1120 for n in range(1,len(input_hist)-1):
1121 1121 log_write(input_hist[n].rstrip())
1122 1122 if n in output_hist:
1123 1123 log_write(repr(output_hist[n]),'output')
1124 1124 else:
1125 1125 logger.log_write(input_hist[1:])
1126 1126 if timestamp:
1127 1127 # re-enable timestamping
1128 1128 logger.timestamp = True
1129 1129
1130 1130 print ('Activating auto-logging. '
1131 1131 'Current session state plus future input saved.')
1132 1132 logger.logstate()
1133 1133
1134 1134 def magic_logstop(self,parameter_s=''):
1135 1135 """Fully stop logging and close log file.
1136 1136
1137 1137 In order to start logging again, a new %logstart call needs to be made,
1138 1138 possibly (though not necessarily) with a new filename, mode and other
1139 1139 options."""
1140 1140 self.logger.logstop()
1141 1141
1142 1142 def magic_logoff(self,parameter_s=''):
1143 1143 """Temporarily stop logging.
1144 1144
1145 1145 You must have previously started logging."""
1146 1146 self.shell.logger.switch_log(0)
1147 1147
1148 1148 def magic_logon(self,parameter_s=''):
1149 1149 """Restart logging.
1150 1150
1151 1151 This function is for restarting logging which you've temporarily
1152 1152 stopped with %logoff. For starting logging for the first time, you
1153 1153 must use the %logstart function, which allows you to specify an
1154 1154 optional log filename."""
1155 1155
1156 1156 self.shell.logger.switch_log(1)
1157 1157
1158 1158 def magic_logstate(self,parameter_s=''):
1159 1159 """Print the status of the logging system."""
1160 1160
1161 1161 self.shell.logger.logstate()
1162 1162
1163 1163 def magic_pdb(self, parameter_s=''):
1164 1164 """Control the automatic calling of the pdb interactive debugger.
1165 1165
1166 1166 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1167 1167 argument it works as a toggle.
1168 1168
1169 1169 When an exception is triggered, IPython can optionally call the
1170 1170 interactive pdb debugger after the traceback printout. %pdb toggles
1171 1171 this feature on and off.
1172 1172
1173 1173 The initial state of this feature is set in your ipythonrc
1174 1174 configuration file (the variable is called 'pdb').
1175 1175
1176 1176 If you want to just activate the debugger AFTER an exception has fired,
1177 1177 without having to type '%pdb on' and rerunning your code, you can use
1178 1178 the %debug magic."""
1179 1179
1180 1180 par = parameter_s.strip().lower()
1181 1181
1182 1182 if par:
1183 1183 try:
1184 1184 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
1185 1185 except KeyError:
1186 1186 print ('Incorrect argument. Use on/1, off/0, '
1187 1187 'or nothing for a toggle.')
1188 1188 return
1189 1189 else:
1190 1190 # toggle
1191 1191 new_pdb = not self.shell.call_pdb
1192 1192
1193 1193 # set on the shell
1194 1194 self.shell.call_pdb = new_pdb
1195 1195 print 'Automatic pdb calling has been turned',on_off(new_pdb)
1196 1196
1197 1197 def magic_debug(self, parameter_s=''):
1198 1198 """Activate the interactive debugger in post-mortem mode.
1199 1199
1200 1200 If an exception has just occurred, this lets you inspect its stack
1201 1201 frames interactively. Note that this will always work only on the last
1202 1202 traceback that occurred, so you must call this quickly after an
1203 1203 exception that you wish to inspect has fired, because if another one
1204 1204 occurs, it clobbers the previous one.
1205 1205
1206 1206 If you want IPython to automatically do this on every exception, see
1207 1207 the %pdb magic for more details.
1208 1208 """
1209 1209 self.shell.debugger(force=True)
1210 1210
1211 1211 @testdec.skip_doctest
1212 1212 def magic_prun(self, parameter_s ='',user_mode=1,
1213 1213 opts=None,arg_lst=None,prog_ns=None):
1214 1214
1215 1215 """Run a statement through the python code profiler.
1216 1216
1217 1217 Usage:
1218 1218 %prun [options] statement
1219 1219
1220 1220 The given statement (which doesn't require quote marks) is run via the
1221 1221 python profiler in a manner similar to the profile.run() function.
1222 1222 Namespaces are internally managed to work correctly; profile.run
1223 1223 cannot be used in IPython because it makes certain assumptions about
1224 1224 namespaces which do not hold under IPython.
1225 1225
1226 1226 Options:
1227 1227
1228 1228 -l <limit>: you can place restrictions on what or how much of the
1229 1229 profile gets printed. The limit value can be:
1230 1230
1231 1231 * A string: only information for function names containing this string
1232 1232 is printed.
1233 1233
1234 1234 * An integer: only these many lines are printed.
1235 1235
1236 1236 * A float (between 0 and 1): this fraction of the report is printed
1237 1237 (for example, use a limit of 0.4 to see the topmost 40% only).
1238 1238
1239 1239 You can combine several limits with repeated use of the option. For
1240 1240 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1241 1241 information about class constructors.
1242 1242
1243 1243 -r: return the pstats.Stats object generated by the profiling. This
1244 1244 object has all the information about the profile in it, and you can
1245 1245 later use it for further analysis or in other functions.
1246 1246
1247 1247 -s <key>: sort profile by given key. You can provide more than one key
1248 1248 by using the option several times: '-s key1 -s key2 -s key3...'. The
1249 1249 default sorting key is 'time'.
1250 1250
1251 1251 The following is copied verbatim from the profile documentation
1252 1252 referenced below:
1253 1253
1254 1254 When more than one key is provided, additional keys are used as
1255 1255 secondary criteria when the there is equality in all keys selected
1256 1256 before them.
1257 1257
1258 1258 Abbreviations can be used for any key names, as long as the
1259 1259 abbreviation is unambiguous. The following are the keys currently
1260 1260 defined:
1261 1261
1262 1262 Valid Arg Meaning
1263 1263 "calls" call count
1264 1264 "cumulative" cumulative time
1265 1265 "file" file name
1266 1266 "module" file name
1267 1267 "pcalls" primitive call count
1268 1268 "line" line number
1269 1269 "name" function name
1270 1270 "nfl" name/file/line
1271 1271 "stdname" standard name
1272 1272 "time" internal time
1273 1273
1274 1274 Note that all sorts on statistics are in descending order (placing
1275 1275 most time consuming items first), where as name, file, and line number
1276 1276 searches are in ascending order (i.e., alphabetical). The subtle
1277 1277 distinction between "nfl" and "stdname" is that the standard name is a
1278 1278 sort of the name as printed, which means that the embedded line
1279 1279 numbers get compared in an odd way. For example, lines 3, 20, and 40
1280 1280 would (if the file names were the same) appear in the string order
1281 1281 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1282 1282 line numbers. In fact, sort_stats("nfl") is the same as
1283 1283 sort_stats("name", "file", "line").
1284 1284
1285 1285 -T <filename>: save profile results as shown on screen to a text
1286 1286 file. The profile is still shown on screen.
1287 1287
1288 1288 -D <filename>: save (via dump_stats) profile statistics to given
1289 1289 filename. This data is in a format understod by the pstats module, and
1290 1290 is generated by a call to the dump_stats() method of profile
1291 1291 objects. The profile is still shown on screen.
1292 1292
1293 1293 If you want to run complete programs under the profiler's control, use
1294 1294 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1295 1295 contains profiler specific options as described here.
1296 1296
1297 1297 You can read the complete documentation for the profile module with::
1298 1298
1299 1299 In [1]: import profile; profile.help()
1300 1300 """
1301 1301
1302 1302 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1303 1303 # protect user quote marks
1304 1304 parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'")
1305 1305
1306 1306 if user_mode: # regular user call
1307 1307 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:',
1308 1308 list_all=1)
1309 1309 namespace = self.shell.user_ns
1310 1310 else: # called to run a program by %run -p
1311 1311 try:
1312 1312 filename = get_py_filename(arg_lst[0])
1313 1313 except IOError,msg:
1314 1314 error(msg)
1315 1315 return
1316 1316
1317 1317 arg_str = 'execfile(filename,prog_ns)'
1318 1318 namespace = locals()
1319 1319
1320 1320 opts.merge(opts_def)
1321 1321
1322 1322 prof = profile.Profile()
1323 1323 try:
1324 1324 prof = prof.runctx(arg_str,namespace,namespace)
1325 1325 sys_exit = ''
1326 1326 except SystemExit:
1327 1327 sys_exit = """*** SystemExit exception caught in code being profiled."""
1328 1328
1329 1329 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1330 1330
1331 1331 lims = opts.l
1332 1332 if lims:
1333 1333 lims = [] # rebuild lims with ints/floats/strings
1334 1334 for lim in opts.l:
1335 1335 try:
1336 1336 lims.append(int(lim))
1337 1337 except ValueError:
1338 1338 try:
1339 1339 lims.append(float(lim))
1340 1340 except ValueError:
1341 1341 lims.append(lim)
1342 1342
1343 1343 # Trap output.
1344 1344 stdout_trap = StringIO()
1345 1345
1346 1346 if hasattr(stats,'stream'):
1347 1347 # In newer versions of python, the stats object has a 'stream'
1348 1348 # attribute to write into.
1349 1349 stats.stream = stdout_trap
1350 1350 stats.print_stats(*lims)
1351 1351 else:
1352 1352 # For older versions, we manually redirect stdout during printing
1353 1353 sys_stdout = sys.stdout
1354 1354 try:
1355 1355 sys.stdout = stdout_trap
1356 1356 stats.print_stats(*lims)
1357 1357 finally:
1358 1358 sys.stdout = sys_stdout
1359 1359
1360 1360 output = stdout_trap.getvalue()
1361 1361 output = output.rstrip()
1362 1362
1363 1363 page.page(output)
1364 1364 print sys_exit,
1365 1365
1366 1366 dump_file = opts.D[0]
1367 1367 text_file = opts.T[0]
1368 1368 if dump_file:
1369 1369 prof.dump_stats(dump_file)
1370 1370 print '\n*** Profile stats marshalled to file',\
1371 1371 `dump_file`+'.',sys_exit
1372 1372 if text_file:
1373 1373 pfile = file(text_file,'w')
1374 1374 pfile.write(output)
1375 1375 pfile.close()
1376 1376 print '\n*** Profile printout saved to text file',\
1377 1377 `text_file`+'.',sys_exit
1378 1378
1379 1379 if opts.has_key('r'):
1380 1380 return stats
1381 1381 else:
1382 1382 return None
1383 1383
1384 1384 @testdec.skip_doctest
1385 1385 def magic_run(self, parameter_s ='',runner=None,
1386 1386 file_finder=get_py_filename):
1387 1387 """Run the named file inside IPython as a program.
1388 1388
1389 1389 Usage:\\
1390 1390 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1391 1391
1392 1392 Parameters after the filename are passed as command-line arguments to
1393 1393 the program (put in sys.argv). Then, control returns to IPython's
1394 1394 prompt.
1395 1395
1396 1396 This is similar to running at a system prompt:\\
1397 1397 $ python file args\\
1398 1398 but with the advantage of giving you IPython's tracebacks, and of
1399 1399 loading all variables into your interactive namespace for further use
1400 1400 (unless -p is used, see below).
1401 1401
1402 1402 The file is executed in a namespace initially consisting only of
1403 1403 __name__=='__main__' and sys.argv constructed as indicated. It thus
1404 1404 sees its environment as if it were being run as a stand-alone program
1405 1405 (except for sharing global objects such as previously imported
1406 1406 modules). But after execution, the IPython interactive namespace gets
1407 1407 updated with all variables defined in the program (except for __name__
1408 1408 and sys.argv). This allows for very convenient loading of code for
1409 1409 interactive work, while giving each program a 'clean sheet' to run in.
1410 1410
1411 1411 Options:
1412 1412
1413 1413 -n: __name__ is NOT set to '__main__', but to the running file's name
1414 1414 without extension (as python does under import). This allows running
1415 1415 scripts and reloading the definitions in them without calling code
1416 1416 protected by an ' if __name__ == "__main__" ' clause.
1417 1417
1418 1418 -i: run the file in IPython's namespace instead of an empty one. This
1419 1419 is useful if you are experimenting with code written in a text editor
1420 1420 which depends on variables defined interactively.
1421 1421
1422 1422 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1423 1423 being run. This is particularly useful if IPython is being used to
1424 1424 run unittests, which always exit with a sys.exit() call. In such
1425 1425 cases you are interested in the output of the test results, not in
1426 1426 seeing a traceback of the unittest module.
1427 1427
1428 1428 -t: print timing information at the end of the run. IPython will give
1429 1429 you an estimated CPU time consumption for your script, which under
1430 1430 Unix uses the resource module to avoid the wraparound problems of
1431 1431 time.clock(). Under Unix, an estimate of time spent on system tasks
1432 1432 is also given (for Windows platforms this is reported as 0.0).
1433 1433
1434 1434 If -t is given, an additional -N<N> option can be given, where <N>
1435 1435 must be an integer indicating how many times you want the script to
1436 1436 run. The final timing report will include total and per run results.
1437 1437
1438 1438 For example (testing the script uniq_stable.py):
1439 1439
1440 1440 In [1]: run -t uniq_stable
1441 1441
1442 1442 IPython CPU timings (estimated):\\
1443 1443 User : 0.19597 s.\\
1444 1444 System: 0.0 s.\\
1445 1445
1446 1446 In [2]: run -t -N5 uniq_stable
1447 1447
1448 1448 IPython CPU timings (estimated):\\
1449 1449 Total runs performed: 5\\
1450 1450 Times : Total Per run\\
1451 1451 User : 0.910862 s, 0.1821724 s.\\
1452 1452 System: 0.0 s, 0.0 s.
1453 1453
1454 1454 -d: run your program under the control of pdb, the Python debugger.
1455 1455 This allows you to execute your program step by step, watch variables,
1456 1456 etc. Internally, what IPython does is similar to calling:
1457 1457
1458 1458 pdb.run('execfile("YOURFILENAME")')
1459 1459
1460 1460 with a breakpoint set on line 1 of your file. You can change the line
1461 1461 number for this automatic breakpoint to be <N> by using the -bN option
1462 1462 (where N must be an integer). For example:
1463 1463
1464 1464 %run -d -b40 myscript
1465 1465
1466 1466 will set the first breakpoint at line 40 in myscript.py. Note that
1467 1467 the first breakpoint must be set on a line which actually does
1468 1468 something (not a comment or docstring) for it to stop execution.
1469 1469
1470 1470 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1471 1471 first enter 'c' (without qoutes) to start execution up to the first
1472 1472 breakpoint.
1473 1473
1474 1474 Entering 'help' gives information about the use of the debugger. You
1475 1475 can easily see pdb's full documentation with "import pdb;pdb.help()"
1476 1476 at a prompt.
1477 1477
1478 1478 -p: run program under the control of the Python profiler module (which
1479 1479 prints a detailed report of execution times, function calls, etc).
1480 1480
1481 1481 You can pass other options after -p which affect the behavior of the
1482 1482 profiler itself. See the docs for %prun for details.
1483 1483
1484 1484 In this mode, the program's variables do NOT propagate back to the
1485 1485 IPython interactive namespace (because they remain in the namespace
1486 1486 where the profiler executes them).
1487 1487
1488 1488 Internally this triggers a call to %prun, see its documentation for
1489 1489 details on the options available specifically for profiling.
1490 1490
1491 1491 There is one special usage for which the text above doesn't apply:
1492 1492 if the filename ends with .ipy, the file is run as ipython script,
1493 1493 just as if the commands were written on IPython prompt.
1494 1494 """
1495 1495
1496 1496 # get arguments and set sys.argv for program to be run.
1497 1497 opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e',
1498 1498 mode='list',list_all=1)
1499 1499
1500 1500 try:
1501 1501 filename = file_finder(arg_lst[0])
1502 1502 except IndexError:
1503 1503 warn('you must provide at least a filename.')
1504 1504 print '\n%run:\n',oinspect.getdoc(self.magic_run)
1505 1505 return
1506 1506 except IOError,msg:
1507 1507 error(msg)
1508 1508 return
1509 1509
1510 1510 if filename.lower().endswith('.ipy'):
1511 1511 self.shell.safe_execfile_ipy(filename)
1512 1512 return
1513 1513
1514 1514 # Control the response to exit() calls made by the script being run
1515 1515 exit_ignore = opts.has_key('e')
1516 1516
1517 1517 # Make sure that the running script gets a proper sys.argv as if it
1518 1518 # were run from a system shell.
1519 1519 save_argv = sys.argv # save it for later restoring
1520 1520 sys.argv = [filename]+ arg_lst[1:] # put in the proper filename
1521 1521
1522 1522 if opts.has_key('i'):
1523 1523 # Run in user's interactive namespace
1524 1524 prog_ns = self.shell.user_ns
1525 1525 __name__save = self.shell.user_ns['__name__']
1526 1526 prog_ns['__name__'] = '__main__'
1527 1527 main_mod = self.shell.new_main_mod(prog_ns)
1528 1528 else:
1529 1529 # Run in a fresh, empty namespace
1530 1530 if opts.has_key('n'):
1531 1531 name = os.path.splitext(os.path.basename(filename))[0]
1532 1532 else:
1533 1533 name = '__main__'
1534 1534
1535 1535 main_mod = self.shell.new_main_mod()
1536 1536 prog_ns = main_mod.__dict__
1537 1537 prog_ns['__name__'] = name
1538 1538
1539 1539 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
1540 1540 # set the __file__ global in the script's namespace
1541 1541 prog_ns['__file__'] = filename
1542 1542
1543 1543 # pickle fix. See interactiveshell for an explanation. But we need to make sure
1544 1544 # that, if we overwrite __main__, we replace it at the end
1545 1545 main_mod_name = prog_ns['__name__']
1546 1546
1547 1547 if main_mod_name == '__main__':
1548 1548 restore_main = sys.modules['__main__']
1549 1549 else:
1550 1550 restore_main = False
1551 1551
1552 1552 # This needs to be undone at the end to prevent holding references to
1553 1553 # every single object ever created.
1554 1554 sys.modules[main_mod_name] = main_mod
1555 1555
1556 1556 stats = None
1557 1557 try:
1558 1558 self.shell.savehist()
1559 1559
1560 1560 if opts.has_key('p'):
1561 1561 stats = self.magic_prun('',0,opts,arg_lst,prog_ns)
1562 1562 else:
1563 1563 if opts.has_key('d'):
1564 1564 deb = debugger.Pdb(self.shell.colors)
1565 1565 # reset Breakpoint state, which is moronically kept
1566 1566 # in a class
1567 1567 bdb.Breakpoint.next = 1
1568 1568 bdb.Breakpoint.bplist = {}
1569 1569 bdb.Breakpoint.bpbynumber = [None]
1570 1570 # Set an initial breakpoint to stop execution
1571 1571 maxtries = 10
1572 1572 bp = int(opts.get('b',[1])[0])
1573 1573 checkline = deb.checkline(filename,bp)
1574 1574 if not checkline:
1575 1575 for bp in range(bp+1,bp+maxtries+1):
1576 1576 if deb.checkline(filename,bp):
1577 1577 break
1578 1578 else:
1579 1579 msg = ("\nI failed to find a valid line to set "
1580 1580 "a breakpoint\n"
1581 1581 "after trying up to line: %s.\n"
1582 1582 "Please set a valid breakpoint manually "
1583 1583 "with the -b option." % bp)
1584 1584 error(msg)
1585 1585 return
1586 1586 # if we find a good linenumber, set the breakpoint
1587 1587 deb.do_break('%s:%s' % (filename,bp))
1588 1588 # Start file run
1589 1589 print "NOTE: Enter 'c' at the",
1590 1590 print "%s prompt to start your script." % deb.prompt
1591 1591 try:
1592 1592 deb.run('execfile("%s")' % filename,prog_ns)
1593 1593
1594 1594 except:
1595 1595 etype, value, tb = sys.exc_info()
1596 1596 # Skip three frames in the traceback: the %run one,
1597 1597 # one inside bdb.py, and the command-line typed by the
1598 1598 # user (run by exec in pdb itself).
1599 1599 self.shell.InteractiveTB(etype,value,tb,tb_offset=3)
1600 1600 else:
1601 1601 if runner is None:
1602 1602 runner = self.shell.safe_execfile
1603 1603 if opts.has_key('t'):
1604 1604 # timed execution
1605 1605 try:
1606 1606 nruns = int(opts['N'][0])
1607 1607 if nruns < 1:
1608 1608 error('Number of runs must be >=1')
1609 1609 return
1610 1610 except (KeyError):
1611 1611 nruns = 1
1612 1612 if nruns == 1:
1613 1613 t0 = clock2()
1614 1614 runner(filename,prog_ns,prog_ns,
1615 1615 exit_ignore=exit_ignore)
1616 1616 t1 = clock2()
1617 1617 t_usr = t1[0]-t0[0]
1618 1618 t_sys = t1[1]-t0[1]
1619 1619 print "\nIPython CPU timings (estimated):"
1620 1620 print " User : %10s s." % t_usr
1621 1621 print " System: %10s s." % t_sys
1622 1622 else:
1623 1623 runs = range(nruns)
1624 1624 t0 = clock2()
1625 1625 for nr in runs:
1626 1626 runner(filename,prog_ns,prog_ns,
1627 1627 exit_ignore=exit_ignore)
1628 1628 t1 = clock2()
1629 1629 t_usr = t1[0]-t0[0]
1630 1630 t_sys = t1[1]-t0[1]
1631 1631 print "\nIPython CPU timings (estimated):"
1632 1632 print "Total runs performed:",nruns
1633 1633 print " Times : %10s %10s" % ('Total','Per run')
1634 1634 print " User : %10s s, %10s s." % (t_usr,t_usr/nruns)
1635 1635 print " System: %10s s, %10s s." % (t_sys,t_sys/nruns)
1636 1636
1637 1637 else:
1638 1638 # regular execution
1639 1639 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1640 1640
1641 1641 if opts.has_key('i'):
1642 1642 self.shell.user_ns['__name__'] = __name__save
1643 1643 else:
1644 1644 # The shell MUST hold a reference to prog_ns so after %run
1645 1645 # exits, the python deletion mechanism doesn't zero it out
1646 1646 # (leaving dangling references).
1647 1647 self.shell.cache_main_mod(prog_ns,filename)
1648 1648 # update IPython interactive namespace
1649 1649
1650 1650 # Some forms of read errors on the file may mean the
1651 1651 # __name__ key was never set; using pop we don't have to
1652 1652 # worry about a possible KeyError.
1653 1653 prog_ns.pop('__name__', None)
1654 1654
1655 1655 self.shell.user_ns.update(prog_ns)
1656 1656 finally:
1657 1657 # It's a bit of a mystery why, but __builtins__ can change from
1658 1658 # being a module to becoming a dict missing some key data after
1659 1659 # %run. As best I can see, this is NOT something IPython is doing
1660 1660 # at all, and similar problems have been reported before:
1661 1661 # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html
1662 1662 # Since this seems to be done by the interpreter itself, the best
1663 1663 # we can do is to at least restore __builtins__ for the user on
1664 1664 # exit.
1665 1665 self.shell.user_ns['__builtins__'] = __builtin__
1666 1666
1667 1667 # Ensure key global structures are restored
1668 1668 sys.argv = save_argv
1669 1669 if restore_main:
1670 1670 sys.modules['__main__'] = restore_main
1671 1671 else:
1672 1672 # Remove from sys.modules the reference to main_mod we'd
1673 1673 # added. Otherwise it will trap references to objects
1674 1674 # contained therein.
1675 1675 del sys.modules[main_mod_name]
1676 1676
1677 1677 self.shell.reloadhist()
1678 1678
1679 1679 return stats
1680 1680
1681 1681 @testdec.skip_doctest
1682 1682 def magic_timeit(self, parameter_s =''):
1683 1683 """Time execution of a Python statement or expression
1684 1684
1685 1685 Usage:\\
1686 1686 %timeit [-n<N> -r<R> [-t|-c]] statement
1687 1687
1688 1688 Time execution of a Python statement or expression using the timeit
1689 1689 module.
1690 1690
1691 1691 Options:
1692 1692 -n<N>: execute the given statement <N> times in a loop. If this value
1693 1693 is not given, a fitting value is chosen.
1694 1694
1695 1695 -r<R>: repeat the loop iteration <R> times and take the best result.
1696 1696 Default: 3
1697 1697
1698 1698 -t: use time.time to measure the time, which is the default on Unix.
1699 1699 This function measures wall time.
1700 1700
1701 1701 -c: use time.clock to measure the time, which is the default on
1702 1702 Windows and measures wall time. On Unix, resource.getrusage is used
1703 1703 instead and returns the CPU user time.
1704 1704
1705 1705 -p<P>: use a precision of <P> digits to display the timing result.
1706 1706 Default: 3
1707 1707
1708 1708
1709 1709 Examples:
1710 1710
1711 1711 In [1]: %timeit pass
1712 1712 10000000 loops, best of 3: 53.3 ns per loop
1713 1713
1714 1714 In [2]: u = None
1715 1715
1716 1716 In [3]: %timeit u is None
1717 1717 10000000 loops, best of 3: 184 ns per loop
1718 1718
1719 1719 In [4]: %timeit -r 4 u == None
1720 1720 1000000 loops, best of 4: 242 ns per loop
1721 1721
1722 1722 In [5]: import time
1723 1723
1724 1724 In [6]: %timeit -n1 time.sleep(2)
1725 1725 1 loops, best of 3: 2 s per loop
1726 1726
1727 1727
1728 1728 The times reported by %timeit will be slightly higher than those
1729 1729 reported by the timeit.py script when variables are accessed. This is
1730 1730 due to the fact that %timeit executes the statement in the namespace
1731 1731 of the shell, compared with timeit.py, which uses a single setup
1732 1732 statement to import function or create variables. Generally, the bias
1733 1733 does not matter as long as results from timeit.py are not mixed with
1734 1734 those from %timeit."""
1735 1735
1736 1736 import timeit
1737 1737 import math
1738 1738
1739 1739 # XXX: Unfortunately the unicode 'micro' symbol can cause problems in
1740 1740 # certain terminals. Until we figure out a robust way of
1741 1741 # auto-detecting if the terminal can deal with it, use plain 'us' for
1742 1742 # microseconds. I am really NOT happy about disabling the proper
1743 1743 # 'micro' prefix, but crashing is worse... If anyone knows what the
1744 1744 # right solution for this is, I'm all ears...
1745 1745 #
1746 1746 # Note: using
1747 1747 #
1748 1748 # s = u'\xb5'
1749 1749 # s.encode(sys.getdefaultencoding())
1750 1750 #
1751 1751 # is not sufficient, as I've seen terminals where that fails but
1752 1752 # print s
1753 1753 #
1754 1754 # succeeds
1755 1755 #
1756 1756 # See bug: https://bugs.launchpad.net/ipython/+bug/348466
1757 1757
1758 1758 #units = [u"s", u"ms",u'\xb5',"ns"]
1759 1759 units = [u"s", u"ms",u'us',"ns"]
1760 1760
1761 1761 scaling = [1, 1e3, 1e6, 1e9]
1762 1762
1763 1763 opts, stmt = self.parse_options(parameter_s,'n:r:tcp:',
1764 1764 posix=False)
1765 1765 if stmt == "":
1766 1766 return
1767 1767 timefunc = timeit.default_timer
1768 1768 number = int(getattr(opts, "n", 0))
1769 1769 repeat = int(getattr(opts, "r", timeit.default_repeat))
1770 1770 precision = int(getattr(opts, "p", 3))
1771 1771 if hasattr(opts, "t"):
1772 1772 timefunc = time.time
1773 1773 if hasattr(opts, "c"):
1774 1774 timefunc = clock
1775 1775
1776 1776 timer = timeit.Timer(timer=timefunc)
1777 1777 # this code has tight coupling to the inner workings of timeit.Timer,
1778 1778 # but is there a better way to achieve that the code stmt has access
1779 1779 # to the shell namespace?
1780 1780
1781 1781 src = timeit.template % {'stmt': timeit.reindent(stmt, 8),
1782 1782 'setup': "pass"}
1783 1783 # Track compilation time so it can be reported if too long
1784 1784 # Minimum time above which compilation time will be reported
1785 1785 tc_min = 0.1
1786 1786
1787 1787 t0 = clock()
1788 1788 code = compile(src, "<magic-timeit>", "exec")
1789 1789 tc = clock()-t0
1790 1790
1791 1791 ns = {}
1792 1792 exec code in self.shell.user_ns, ns
1793 1793 timer.inner = ns["inner"]
1794 1794
1795 1795 if number == 0:
1796 1796 # determine number so that 0.2 <= total time < 2.0
1797 1797 number = 1
1798 1798 for i in range(1, 10):
1799 1799 if timer.timeit(number) >= 0.2:
1800 1800 break
1801 1801 number *= 10
1802 1802
1803 1803 best = min(timer.repeat(repeat, number)) / number
1804 1804
1805 1805 if best > 0.0 and best < 1000.0:
1806 1806 order = min(-int(math.floor(math.log10(best)) // 3), 3)
1807 1807 elif best >= 1000.0:
1808 1808 order = 0
1809 1809 else:
1810 1810 order = 3
1811 1811 print u"%d loops, best of %d: %.*g %s per loop" % (number, repeat,
1812 1812 precision,
1813 1813 best * scaling[order],
1814 1814 units[order])
1815 1815 if tc > tc_min:
1816 1816 print "Compiler time: %.2f s" % tc
1817 1817
1818 1818 @testdec.skip_doctest
1819 1819 def magic_time(self,parameter_s = ''):
1820 1820 """Time execution of a Python statement or expression.
1821 1821
1822 1822 The CPU and wall clock times are printed, and the value of the
1823 1823 expression (if any) is returned. Note that under Win32, system time
1824 1824 is always reported as 0, since it can not be measured.
1825 1825
1826 1826 This function provides very basic timing functionality. In Python
1827 1827 2.3, the timeit module offers more control and sophistication, so this
1828 1828 could be rewritten to use it (patches welcome).
1829 1829
1830 1830 Some examples:
1831 1831
1832 1832 In [1]: time 2**128
1833 1833 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1834 1834 Wall time: 0.00
1835 1835 Out[1]: 340282366920938463463374607431768211456L
1836 1836
1837 1837 In [2]: n = 1000000
1838 1838
1839 1839 In [3]: time sum(range(n))
1840 1840 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1841 1841 Wall time: 1.37
1842 1842 Out[3]: 499999500000L
1843 1843
1844 1844 In [4]: time print 'hello world'
1845 1845 hello world
1846 1846 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1847 1847 Wall time: 0.00
1848 1848
1849 1849 Note that the time needed by Python to compile the given expression
1850 1850 will be reported if it is more than 0.1s. In this example, the
1851 1851 actual exponentiation is done by Python at compilation time, so while
1852 1852 the expression can take a noticeable amount of time to compute, that
1853 1853 time is purely due to the compilation:
1854 1854
1855 1855 In [5]: time 3**9999;
1856 1856 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1857 1857 Wall time: 0.00 s
1858 1858
1859 1859 In [6]: time 3**999999;
1860 1860 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1861 1861 Wall time: 0.00 s
1862 1862 Compiler : 0.78 s
1863 1863 """
1864 1864
1865 1865 # fail immediately if the given expression can't be compiled
1866 1866
1867 1867 expr = self.shell.prefilter(parameter_s,False)
1868 1868
1869 1869 # Minimum time above which compilation time will be reported
1870 1870 tc_min = 0.1
1871 1871
1872 1872 try:
1873 1873 mode = 'eval'
1874 1874 t0 = clock()
1875 1875 code = compile(expr,'<timed eval>',mode)
1876 1876 tc = clock()-t0
1877 1877 except SyntaxError:
1878 1878 mode = 'exec'
1879 1879 t0 = clock()
1880 1880 code = compile(expr,'<timed exec>',mode)
1881 1881 tc = clock()-t0
1882 1882 # skew measurement as little as possible
1883 1883 glob = self.shell.user_ns
1884 1884 clk = clock2
1885 1885 wtime = time.time
1886 1886 # time execution
1887 1887 wall_st = wtime()
1888 1888 if mode=='eval':
1889 1889 st = clk()
1890 1890 out = eval(code,glob)
1891 1891 end = clk()
1892 1892 else:
1893 1893 st = clk()
1894 1894 exec code in glob
1895 1895 end = clk()
1896 1896 out = None
1897 1897 wall_end = wtime()
1898 1898 # Compute actual times and report
1899 1899 wall_time = wall_end-wall_st
1900 1900 cpu_user = end[0]-st[0]
1901 1901 cpu_sys = end[1]-st[1]
1902 1902 cpu_tot = cpu_user+cpu_sys
1903 1903 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
1904 1904 (cpu_user,cpu_sys,cpu_tot)
1905 1905 print "Wall time: %.2f s" % wall_time
1906 1906 if tc > tc_min:
1907 1907 print "Compiler : %.2f s" % tc
1908 1908 return out
1909 1909
1910 1910 @testdec.skip_doctest
1911 1911 def magic_macro(self,parameter_s = ''):
1912 1912 """Define a set of input lines as a macro for future re-execution.
1913 1913
1914 1914 Usage:\\
1915 1915 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
1916 1916
1917 1917 Options:
1918 1918
1919 1919 -r: use 'raw' input. By default, the 'processed' history is used,
1920 1920 so that magics are loaded in their transformed version to valid
1921 1921 Python. If this option is given, the raw input as typed as the
1922 1922 command line is used instead.
1923 1923
1924 1924 This will define a global variable called `name` which is a string
1925 1925 made of joining the slices and lines you specify (n1,n2,... numbers
1926 1926 above) from your input history into a single string. This variable
1927 1927 acts like an automatic function which re-executes those lines as if
1928 1928 you had typed them. You just type 'name' at the prompt and the code
1929 1929 executes.
1930 1930
1931 1931 The notation for indicating number ranges is: n1-n2 means 'use line
1932 1932 numbers n1,...n2' (the endpoint is included). That is, '5-7' means
1933 1933 using the lines numbered 5,6 and 7.
1934 1934
1935 1935 Note: as a 'hidden' feature, you can also use traditional python slice
1936 1936 notation, where N:M means numbers N through M-1.
1937 1937
1938 1938 For example, if your history contains (%hist prints it):
1939 1939
1940 1940 44: x=1
1941 1941 45: y=3
1942 1942 46: z=x+y
1943 1943 47: print x
1944 1944 48: a=5
1945 1945 49: print 'x',x,'y',y
1946 1946
1947 1947 you can create a macro with lines 44 through 47 (included) and line 49
1948 1948 called my_macro with:
1949 1949
1950 1950 In [55]: %macro my_macro 44-47 49
1951 1951
1952 1952 Now, typing `my_macro` (without quotes) will re-execute all this code
1953 1953 in one pass.
1954 1954
1955 1955 You don't need to give the line-numbers in order, and any given line
1956 1956 number can appear multiple times. You can assemble macros with any
1957 1957 lines from your input history in any order.
1958 1958
1959 1959 The macro is a simple object which holds its value in an attribute,
1960 1960 but IPython's display system checks for macros and executes them as
1961 1961 code instead of printing them when you type their name.
1962 1962
1963 1963 You can view a macro's contents by explicitly printing it with:
1964 1964
1965 1965 'print macro_name'.
1966 1966
1967 1967 For one-off cases which DON'T contain magic function calls in them you
1968 1968 can obtain similar results by explicitly executing slices from your
1969 1969 input history with:
1970 1970
1971 1971 In [60]: exec In[44:48]+In[49]"""
1972 1972
1973 1973 opts,args = self.parse_options(parameter_s,'r',mode='list')
1974 1974 if not args:
1975 1975 macs = [k for k,v in self.shell.user_ns.items() if isinstance(v, Macro)]
1976 1976 macs.sort()
1977 1977 return macs
1978 1978 if len(args) == 1:
1979 1979 raise UsageError(
1980 1980 "%macro insufficient args; usage '%macro name n1-n2 n3-4...")
1981 1981 name,ranges = args[0], args[1:]
1982 1982
1983 1983 #print 'rng',ranges # dbg
1984 1984 lines = self.extract_input_slices(ranges,opts.has_key('r'))
1985 1985 macro = Macro(lines)
1986 1986 self.shell.define_macro(name, macro)
1987 1987 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
1988 1988 print 'Macro contents:'
1989 1989 print macro,
1990 1990
1991 1991 def magic_save(self,parameter_s = ''):
1992 1992 """Save a set of lines to a given filename.
1993 1993
1994 1994 Usage:\\
1995 1995 %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ...
1996 1996
1997 1997 Options:
1998 1998
1999 1999 -r: use 'raw' input. By default, the 'processed' history is used,
2000 2000 so that magics are loaded in their transformed version to valid
2001 2001 Python. If this option is given, the raw input as typed as the
2002 2002 command line is used instead.
2003 2003
2004 2004 This function uses the same syntax as %macro for line extraction, but
2005 2005 instead of creating a macro it saves the resulting string to the
2006 2006 filename you specify.
2007 2007
2008 2008 It adds a '.py' extension to the file if you don't do so yourself, and
2009 2009 it asks for confirmation before overwriting existing files."""
2010 2010
2011 2011 opts,args = self.parse_options(parameter_s,'r',mode='list')
2012 2012 fname,ranges = args[0], args[1:]
2013 2013 if not fname.endswith('.py'):
2014 2014 fname += '.py'
2015 2015 if os.path.isfile(fname):
2016 2016 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
2017 2017 if ans.lower() not in ['y','yes']:
2018 2018 print 'Operation cancelled.'
2019 2019 return
2020 2020 cmds = ''.join(self.extract_input_slices(ranges,opts.has_key('r')))
2021 2021 f = file(fname,'w')
2022 2022 f.write(cmds)
2023 2023 f.close()
2024 2024 print 'The following commands were written to file `%s`:' % fname
2025 2025 print cmds
2026 2026
2027 2027 def _edit_macro(self,mname,macro):
2028 2028 """open an editor with the macro data in a file"""
2029 2029 filename = self.shell.mktempfile(macro.value)
2030 2030 self.shell.hooks.editor(filename)
2031 2031
2032 2032 # and make a new macro object, to replace the old one
2033 2033 mfile = open(filename)
2034 2034 mvalue = mfile.read()
2035 2035 mfile.close()
2036 2036 self.shell.user_ns[mname] = Macro(mvalue)
2037 2037
2038 2038 def magic_ed(self,parameter_s=''):
2039 2039 """Alias to %edit."""
2040 2040 return self.magic_edit(parameter_s)
2041 2041
2042 2042 @testdec.skip_doctest
2043 2043 def magic_edit(self,parameter_s='',last_call=['','']):
2044 2044 """Bring up an editor and execute the resulting code.
2045 2045
2046 2046 Usage:
2047 2047 %edit [options] [args]
2048 2048
2049 2049 %edit runs IPython's editor hook. The default version of this hook is
2050 2050 set to call the __IPYTHON__.rc.editor command. This is read from your
2051 2051 environment variable $EDITOR. If this isn't found, it will default to
2052 2052 vi under Linux/Unix and to notepad under Windows. See the end of this
2053 2053 docstring for how to change the editor hook.
2054 2054
2055 2055 You can also set the value of this editor via the command line option
2056 2056 '-editor' or in your ipythonrc file. This is useful if you wish to use
2057 2057 specifically for IPython an editor different from your typical default
2058 2058 (and for Windows users who typically don't set environment variables).
2059 2059
2060 2060 This command allows you to conveniently edit multi-line code right in
2061 2061 your IPython session.
2062 2062
2063 2063 If called without arguments, %edit opens up an empty editor with a
2064 2064 temporary file and will execute the contents of this file when you
2065 2065 close it (don't forget to save it!).
2066 2066
2067 2067
2068 2068 Options:
2069 2069
2070 2070 -n <number>: open the editor at a specified line number. By default,
2071 2071 the IPython editor hook uses the unix syntax 'editor +N filename', but
2072 2072 you can configure this by providing your own modified hook if your
2073 2073 favorite editor supports line-number specifications with a different
2074 2074 syntax.
2075 2075
2076 2076 -p: this will call the editor with the same data as the previous time
2077 2077 it was used, regardless of how long ago (in your current session) it
2078 2078 was.
2079 2079
2080 2080 -r: use 'raw' input. This option only applies to input taken from the
2081 2081 user's history. By default, the 'processed' history is used, so that
2082 2082 magics are loaded in their transformed version to valid Python. If
2083 2083 this option is given, the raw input as typed as the command line is
2084 2084 used instead. When you exit the editor, it will be executed by
2085 2085 IPython's own processor.
2086 2086
2087 2087 -x: do not execute the edited code immediately upon exit. This is
2088 2088 mainly useful if you are editing programs which need to be called with
2089 2089 command line arguments, which you can then do using %run.
2090 2090
2091 2091
2092 2092 Arguments:
2093 2093
2094 2094 If arguments are given, the following possibilites exist:
2095 2095
2096 2096 - The arguments are numbers or pairs of colon-separated numbers (like
2097 2097 1 4:8 9). These are interpreted as lines of previous input to be
2098 2098 loaded into the editor. The syntax is the same of the %macro command.
2099 2099
2100 2100 - If the argument doesn't start with a number, it is evaluated as a
2101 2101 variable and its contents loaded into the editor. You can thus edit
2102 2102 any string which contains python code (including the result of
2103 2103 previous edits).
2104 2104
2105 2105 - If the argument is the name of an object (other than a string),
2106 2106 IPython will try to locate the file where it was defined and open the
2107 2107 editor at the point where it is defined. You can use `%edit function`
2108 2108 to load an editor exactly at the point where 'function' is defined,
2109 2109 edit it and have the file be executed automatically.
2110 2110
2111 2111 If the object is a macro (see %macro for details), this opens up your
2112 2112 specified editor with a temporary file containing the macro's data.
2113 2113 Upon exit, the macro is reloaded with the contents of the file.
2114 2114
2115 2115 Note: opening at an exact line is only supported under Unix, and some
2116 2116 editors (like kedit and gedit up to Gnome 2.8) do not understand the
2117 2117 '+NUMBER' parameter necessary for this feature. Good editors like
2118 2118 (X)Emacs, vi, jed, pico and joe all do.
2119 2119
2120 2120 - If the argument is not found as a variable, IPython will look for a
2121 2121 file with that name (adding .py if necessary) and load it into the
2122 2122 editor. It will execute its contents with execfile() when you exit,
2123 2123 loading any code in the file into your interactive namespace.
2124 2124
2125 2125 After executing your code, %edit will return as output the code you
2126 2126 typed in the editor (except when it was an existing file). This way
2127 2127 you can reload the code in further invocations of %edit as a variable,
2128 2128 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
2129 2129 the output.
2130 2130
2131 2131 Note that %edit is also available through the alias %ed.
2132 2132
2133 2133 This is an example of creating a simple function inside the editor and
2134 2134 then modifying it. First, start up the editor:
2135 2135
2136 2136 In [1]: ed
2137 2137 Editing... done. Executing edited code...
2138 2138 Out[1]: 'def foo():n print "foo() was defined in an editing session"n'
2139 2139
2140 2140 We can then call the function foo():
2141 2141
2142 2142 In [2]: foo()
2143 2143 foo() was defined in an editing session
2144 2144
2145 2145 Now we edit foo. IPython automatically loads the editor with the
2146 2146 (temporary) file where foo() was previously defined:
2147 2147
2148 2148 In [3]: ed foo
2149 2149 Editing... done. Executing edited code...
2150 2150
2151 2151 And if we call foo() again we get the modified version:
2152 2152
2153 2153 In [4]: foo()
2154 2154 foo() has now been changed!
2155 2155
2156 2156 Here is an example of how to edit a code snippet successive
2157 2157 times. First we call the editor:
2158 2158
2159 2159 In [5]: ed
2160 2160 Editing... done. Executing edited code...
2161 2161 hello
2162 2162 Out[5]: "print 'hello'n"
2163 2163
2164 2164 Now we call it again with the previous output (stored in _):
2165 2165
2166 2166 In [6]: ed _
2167 2167 Editing... done. Executing edited code...
2168 2168 hello world
2169 2169 Out[6]: "print 'hello world'n"
2170 2170
2171 2171 Now we call it with the output #8 (stored in _8, also as Out[8]):
2172 2172
2173 2173 In [7]: ed _8
2174 2174 Editing... done. Executing edited code...
2175 2175 hello again
2176 2176 Out[7]: "print 'hello again'n"
2177 2177
2178 2178
2179 2179 Changing the default editor hook:
2180 2180
2181 2181 If you wish to write your own editor hook, you can put it in a
2182 2182 configuration file which you load at startup time. The default hook
2183 2183 is defined in the IPython.core.hooks module, and you can use that as a
2184 2184 starting example for further modifications. That file also has
2185 2185 general instructions on how to set a new hook for use once you've
2186 2186 defined it."""
2187 2187
2188 2188 # FIXME: This function has become a convoluted mess. It needs a
2189 2189 # ground-up rewrite with clean, simple logic.
2190 2190
2191 2191 def make_filename(arg):
2192 2192 "Make a filename from the given args"
2193 2193 try:
2194 2194 filename = get_py_filename(arg)
2195 2195 except IOError:
2196 2196 if args.endswith('.py'):
2197 2197 filename = arg
2198 2198 else:
2199 2199 filename = None
2200 2200 return filename
2201 2201
2202 2202 # custom exceptions
2203 2203 class DataIsObject(Exception): pass
2204 2204
2205 2205 opts,args = self.parse_options(parameter_s,'prxn:')
2206 2206 # Set a few locals from the options for convenience:
2207 2207 opts_p = opts.has_key('p')
2208 2208 opts_r = opts.has_key('r')
2209 2209
2210 2210 # Default line number value
2211 2211 lineno = opts.get('n',None)
2212 2212
2213 2213 if opts_p:
2214 2214 args = '_%s' % last_call[0]
2215 2215 if not self.shell.user_ns.has_key(args):
2216 2216 args = last_call[1]
2217 2217
2218 2218 # use last_call to remember the state of the previous call, but don't
2219 2219 # let it be clobbered by successive '-p' calls.
2220 2220 try:
2221 2221 last_call[0] = self.shell.displayhook.prompt_count
2222 2222 if not opts_p:
2223 2223 last_call[1] = parameter_s
2224 2224 except:
2225 2225 pass
2226 2226
2227 2227 # by default this is done with temp files, except when the given
2228 2228 # arg is a filename
2229 2229 use_temp = 1
2230 2230
2231 2231 if re.match(r'\d',args):
2232 2232 # Mode where user specifies ranges of lines, like in %macro.
2233 2233 # This means that you can't edit files whose names begin with
2234 2234 # numbers this way. Tough.
2235 2235 ranges = args.split()
2236 2236 data = ''.join(self.extract_input_slices(ranges,opts_r))
2237 2237 elif args.endswith('.py'):
2238 2238 filename = make_filename(args)
2239 2239 data = ''
2240 2240 use_temp = 0
2241 2241 elif args:
2242 2242 try:
2243 2243 # Load the parameter given as a variable. If not a string,
2244 2244 # process it as an object instead (below)
2245 2245
2246 2246 #print '*** args',args,'type',type(args) # dbg
2247 2247 data = eval(args,self.shell.user_ns)
2248 2248 if not type(data) in StringTypes:
2249 2249 raise DataIsObject
2250 2250
2251 2251 except (NameError,SyntaxError):
2252 2252 # given argument is not a variable, try as a filename
2253 2253 filename = make_filename(args)
2254 2254 if filename is None:
2255 2255 warn("Argument given (%s) can't be found as a variable "
2256 2256 "or as a filename." % args)
2257 2257 return
2258 2258
2259 2259 data = ''
2260 2260 use_temp = 0
2261 2261 except DataIsObject:
2262 2262
2263 2263 # macros have a special edit function
2264 2264 if isinstance(data,Macro):
2265 2265 self._edit_macro(args,data)
2266 2266 return
2267 2267
2268 2268 # For objects, try to edit the file where they are defined
2269 2269 try:
2270 2270 filename = inspect.getabsfile(data)
2271 2271 if 'fakemodule' in filename.lower() and inspect.isclass(data):
2272 2272 # class created by %edit? Try to find source
2273 2273 # by looking for method definitions instead, the
2274 2274 # __module__ in those classes is FakeModule.
2275 2275 attrs = [getattr(data, aname) for aname in dir(data)]
2276 2276 for attr in attrs:
2277 2277 if not inspect.ismethod(attr):
2278 2278 continue
2279 2279 filename = inspect.getabsfile(attr)
2280 2280 if filename and 'fakemodule' not in filename.lower():
2281 2281 # change the attribute to be the edit target instead
2282 2282 data = attr
2283 2283 break
2284 2284
2285 2285 datafile = 1
2286 2286 except TypeError:
2287 2287 filename = make_filename(args)
2288 2288 datafile = 1
2289 2289 warn('Could not find file where `%s` is defined.\n'
2290 2290 'Opening a file named `%s`' % (args,filename))
2291 2291 # Now, make sure we can actually read the source (if it was in
2292 2292 # a temp file it's gone by now).
2293 2293 if datafile:
2294 2294 try:
2295 2295 if lineno is None:
2296 2296 lineno = inspect.getsourcelines(data)[1]
2297 2297 except IOError:
2298 2298 filename = make_filename(args)
2299 2299 if filename is None:
2300 2300 warn('The file `%s` where `%s` was defined cannot '
2301 2301 'be read.' % (filename,data))
2302 2302 return
2303 2303 use_temp = 0
2304 2304 else:
2305 2305 data = ''
2306 2306
2307 2307 if use_temp:
2308 2308 filename = self.shell.mktempfile(data)
2309 2309 print 'IPython will make a temporary file named:',filename
2310 2310
2311 2311 # do actual editing here
2312 2312 print 'Editing...',
2313 2313 sys.stdout.flush()
2314 2314 try:
2315 2315 # Quote filenames that may have spaces in them
2316 2316 if ' ' in filename:
2317 2317 filename = "%s" % filename
2318 2318 self.shell.hooks.editor(filename,lineno)
2319 2319 except TryNext:
2320 2320 warn('Could not open editor')
2321 2321 return
2322 2322
2323 2323 # XXX TODO: should this be generalized for all string vars?
2324 2324 # For now, this is special-cased to blocks created by cpaste
2325 2325 if args.strip() == 'pasted_block':
2326 2326 self.shell.user_ns['pasted_block'] = file_read(filename)
2327 2327
2328 2328 if opts.has_key('x'): # -x prevents actual execution
2329 2329 print
2330 2330 else:
2331 2331 print 'done. Executing edited code...'
2332 2332 if opts_r:
2333 2333 self.shell.runlines(file_read(filename))
2334 2334 else:
2335 2335 self.shell.safe_execfile(filename,self.shell.user_ns,
2336 2336 self.shell.user_ns)
2337 2337
2338 2338
2339 2339 if use_temp:
2340 2340 try:
2341 2341 return open(filename).read()
2342 2342 except IOError,msg:
2343 2343 if msg.filename == filename:
2344 2344 warn('File not found. Did you forget to save?')
2345 2345 return
2346 2346 else:
2347 2347 self.shell.showtraceback()
2348 2348
2349 2349 def magic_xmode(self,parameter_s = ''):
2350 2350 """Switch modes for the exception handlers.
2351 2351
2352 2352 Valid modes: Plain, Context and Verbose.
2353 2353
2354 2354 If called without arguments, acts as a toggle."""
2355 2355
2356 2356 def xmode_switch_err(name):
2357 2357 warn('Error changing %s exception modes.\n%s' %
2358 2358 (name,sys.exc_info()[1]))
2359 2359
2360 2360 shell = self.shell
2361 2361 new_mode = parameter_s.strip().capitalize()
2362 2362 try:
2363 2363 shell.InteractiveTB.set_mode(mode=new_mode)
2364 2364 print 'Exception reporting mode:',shell.InteractiveTB.mode
2365 2365 except:
2366 2366 xmode_switch_err('user')
2367 2367
2368 2368 def magic_colors(self,parameter_s = ''):
2369 2369 """Switch color scheme for prompts, info system and exception handlers.
2370 2370
2371 2371 Currently implemented schemes: NoColor, Linux, LightBG.
2372 2372
2373 2373 Color scheme names are not case-sensitive."""
2374 2374
2375 2375 def color_switch_err(name):
2376 2376 warn('Error changing %s color schemes.\n%s' %
2377 2377 (name,sys.exc_info()[1]))
2378 2378
2379 2379
2380 2380 new_scheme = parameter_s.strip()
2381 2381 if not new_scheme:
2382 2382 raise UsageError(
2383 2383 "%colors: you must specify a color scheme. See '%colors?'")
2384 2384 return
2385 2385 # local shortcut
2386 2386 shell = self.shell
2387 2387
2388 2388 import IPython.utils.rlineimpl as readline
2389 2389
2390 2390 if not readline.have_readline and sys.platform == "win32":
2391 2391 msg = """\
2392 2392 Proper color support under MS Windows requires the pyreadline library.
2393 2393 You can find it at:
2394 2394 http://ipython.scipy.org/moin/PyReadline/Intro
2395 2395 Gary's readline needs the ctypes module, from:
2396 2396 http://starship.python.net/crew/theller/ctypes
2397 2397 (Note that ctypes is already part of Python versions 2.5 and newer).
2398 2398
2399 2399 Defaulting color scheme to 'NoColor'"""
2400 2400 new_scheme = 'NoColor'
2401 2401 warn(msg)
2402 2402
2403 2403 # readline option is 0
2404 2404 if not shell.has_readline:
2405 2405 new_scheme = 'NoColor'
2406 2406
2407 2407 # Set prompt colors
2408 2408 try:
2409 2409 shell.displayhook.set_colors(new_scheme)
2410 2410 except:
2411 2411 color_switch_err('prompt')
2412 2412 else:
2413 2413 shell.colors = \
2414 2414 shell.displayhook.color_table.active_scheme_name
2415 2415 # Set exception colors
2416 2416 try:
2417 2417 shell.InteractiveTB.set_colors(scheme = new_scheme)
2418 2418 shell.SyntaxTB.set_colors(scheme = new_scheme)
2419 2419 except:
2420 2420 color_switch_err('exception')
2421 2421
2422 2422 # Set info (for 'object?') colors
2423 2423 if shell.color_info:
2424 2424 try:
2425 2425 shell.inspector.set_active_scheme(new_scheme)
2426 2426 except:
2427 2427 color_switch_err('object inspector')
2428 2428 else:
2429 2429 shell.inspector.set_active_scheme('NoColor')
2430 2430
2431 2431 def magic_color_info(self,parameter_s = ''):
2432 2432 """Toggle color_info.
2433 2433
2434 2434 The color_info configuration parameter controls whether colors are
2435 2435 used for displaying object details (by things like %psource, %pfile or
2436 2436 the '?' system). This function toggles this value with each call.
2437 2437
2438 2438 Note that unless you have a fairly recent pager (less works better
2439 2439 than more) in your system, using colored object information displays
2440 2440 will not work properly. Test it and see."""
2441 2441
2442 2442 self.shell.color_info = not self.shell.color_info
2443 2443 self.magic_colors(self.shell.colors)
2444 2444 print 'Object introspection functions have now coloring:',
2445 2445 print ['OFF','ON'][int(self.shell.color_info)]
2446 2446
2447 2447 def magic_Pprint(self, parameter_s=''):
2448 2448 """Toggle pretty printing on/off."""
2449 2449
2450 2450 self.shell.pprint = 1 - self.shell.pprint
2451 2451 print 'Pretty printing has been turned', \
2452 2452 ['OFF','ON'][self.shell.pprint]
2453 2453
2454 2454 def magic_Exit(self, parameter_s=''):
2455 2455 """Exit IPython."""
2456 2456
2457 2457 self.shell.ask_exit()
2458 2458
2459 2459 # Add aliases as magics so all common forms work: exit, quit, Exit, Quit.
2460 2460 magic_exit = magic_quit = magic_Quit = magic_Exit
2461 2461
2462 2462 #......................................................................
2463 2463 # Functions to implement unix shell-type things
2464 2464
2465 2465 @testdec.skip_doctest
2466 2466 def magic_alias(self, parameter_s = ''):
2467 2467 """Define an alias for a system command.
2468 2468
2469 2469 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
2470 2470
2471 2471 Then, typing 'alias_name params' will execute the system command 'cmd
2472 2472 params' (from your underlying operating system).
2473 2473
2474 2474 Aliases have lower precedence than magic functions and Python normal
2475 2475 variables, so if 'foo' is both a Python variable and an alias, the
2476 2476 alias can not be executed until 'del foo' removes the Python variable.
2477 2477
2478 2478 You can use the %l specifier in an alias definition to represent the
2479 2479 whole line when the alias is called. For example:
2480 2480
2481 2481 In [2]: alias bracket echo "Input in brackets: <%l>"
2482 2482 In [3]: bracket hello world
2483 2483 Input in brackets: <hello world>
2484 2484
2485 2485 You can also define aliases with parameters using %s specifiers (one
2486 2486 per parameter):
2487 2487
2488 2488 In [1]: alias parts echo first %s second %s
2489 2489 In [2]: %parts A B
2490 2490 first A second B
2491 2491 In [3]: %parts A
2492 2492 Incorrect number of arguments: 2 expected.
2493 2493 parts is an alias to: 'echo first %s second %s'
2494 2494
2495 2495 Note that %l and %s are mutually exclusive. You can only use one or
2496 2496 the other in your aliases.
2497 2497
2498 2498 Aliases expand Python variables just like system calls using ! or !!
2499 2499 do: all expressions prefixed with '$' get expanded. For details of
2500 2500 the semantic rules, see PEP-215:
2501 2501 http://www.python.org/peps/pep-0215.html. This is the library used by
2502 2502 IPython for variable expansion. If you want to access a true shell
2503 2503 variable, an extra $ is necessary to prevent its expansion by IPython:
2504 2504
2505 2505 In [6]: alias show echo
2506 2506 In [7]: PATH='A Python string'
2507 2507 In [8]: show $PATH
2508 2508 A Python string
2509 2509 In [9]: show $$PATH
2510 2510 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2511 2511
2512 2512 You can use the alias facility to acess all of $PATH. See the %rehash
2513 2513 and %rehashx functions, which automatically create aliases for the
2514 2514 contents of your $PATH.
2515 2515
2516 2516 If called with no parameters, %alias prints the current alias table."""
2517 2517
2518 2518 par = parameter_s.strip()
2519 2519 if not par:
2520 2520 stored = self.db.get('stored_aliases', {} )
2521 2521 aliases = sorted(self.shell.alias_manager.aliases)
2522 2522 # for k, v in stored:
2523 2523 # atab.append(k, v[0])
2524 2524
2525 2525 print "Total number of aliases:", len(aliases)
2526 2526 return aliases
2527 2527
2528 2528 # Now try to define a new one
2529 2529 try:
2530 2530 alias,cmd = par.split(None, 1)
2531 2531 except:
2532 2532 print oinspect.getdoc(self.magic_alias)
2533 2533 else:
2534 2534 self.shell.alias_manager.soft_define_alias(alias, cmd)
2535 2535 # end magic_alias
2536 2536
2537 2537 def magic_unalias(self, parameter_s = ''):
2538 2538 """Remove an alias"""
2539 2539
2540 2540 aname = parameter_s.strip()
2541 2541 self.shell.alias_manager.undefine_alias(aname)
2542 2542 stored = self.db.get('stored_aliases', {} )
2543 2543 if aname in stored:
2544 2544 print "Removing %stored alias",aname
2545 2545 del stored[aname]
2546 2546 self.db['stored_aliases'] = stored
2547 2547
2548 2548
2549 2549 def magic_rehashx(self, parameter_s = ''):
2550 2550 """Update the alias table with all executable files in $PATH.
2551 2551
2552 2552 This version explicitly checks that every entry in $PATH is a file
2553 2553 with execute access (os.X_OK), so it is much slower than %rehash.
2554 2554
2555 2555 Under Windows, it checks executability as a match agains a
2556 2556 '|'-separated string of extensions, stored in the IPython config
2557 2557 variable win_exec_ext. This defaults to 'exe|com|bat'.
2558 2558
2559 2559 This function also resets the root module cache of module completer,
2560 2560 used on slow filesystems.
2561 2561 """
2562 2562 from IPython.core.alias import InvalidAliasError
2563 2563
2564 2564 # for the benefit of module completer in ipy_completers.py
2565 2565 del self.db['rootmodules']
2566 2566
2567 2567 path = [os.path.abspath(os.path.expanduser(p)) for p in
2568 2568 os.environ.get('PATH','').split(os.pathsep)]
2569 2569 path = filter(os.path.isdir,path)
2570 2570
2571 2571 syscmdlist = []
2572 2572 # Now define isexec in a cross platform manner.
2573 2573 if os.name == 'posix':
2574 2574 isexec = lambda fname:os.path.isfile(fname) and \
2575 2575 os.access(fname,os.X_OK)
2576 2576 else:
2577 2577 try:
2578 2578 winext = os.environ['pathext'].replace(';','|').replace('.','')
2579 2579 except KeyError:
2580 2580 winext = 'exe|com|bat|py'
2581 2581 if 'py' not in winext:
2582 2582 winext += '|py'
2583 2583 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2584 2584 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2585 2585 savedir = os.getcwd()
2586 2586
2587 2587 # Now walk the paths looking for executables to alias.
2588 2588 try:
2589 2589 # write the whole loop for posix/Windows so we don't have an if in
2590 2590 # the innermost part
2591 2591 if os.name == 'posix':
2592 2592 for pdir in path:
2593 2593 os.chdir(pdir)
2594 2594 for ff in os.listdir(pdir):
2595 2595 if isexec(ff):
2596 2596 try:
2597 2597 # Removes dots from the name since ipython
2598 2598 # will assume names with dots to be python.
2599 2599 self.shell.alias_manager.define_alias(
2600 2600 ff.replace('.',''), ff)
2601 2601 except InvalidAliasError:
2602 2602 pass
2603 2603 else:
2604 2604 syscmdlist.append(ff)
2605 2605 else:
2606 2606 no_alias = self.shell.alias_manager.no_alias
2607 2607 for pdir in path:
2608 2608 os.chdir(pdir)
2609 2609 for ff in os.listdir(pdir):
2610 2610 base, ext = os.path.splitext(ff)
2611 2611 if isexec(ff) and base.lower() not in no_alias:
2612 2612 if ext.lower() == '.exe':
2613 2613 ff = base
2614 2614 try:
2615 2615 # Removes dots from the name since ipython
2616 2616 # will assume names with dots to be python.
2617 2617 self.shell.alias_manager.define_alias(
2618 2618 base.lower().replace('.',''), ff)
2619 2619 except InvalidAliasError:
2620 2620 pass
2621 2621 syscmdlist.append(ff)
2622 2622 db = self.db
2623 2623 db['syscmdlist'] = syscmdlist
2624 2624 finally:
2625 2625 os.chdir(savedir)
2626 2626
2627 2627 def magic_pwd(self, parameter_s = ''):
2628 2628 """Return the current working directory path."""
2629 2629 return os.getcwd()
2630 2630
2631 2631 def magic_cd(self, parameter_s=''):
2632 2632 """Change the current working directory.
2633 2633
2634 2634 This command automatically maintains an internal list of directories
2635 2635 you visit during your IPython session, in the variable _dh. The
2636 2636 command %dhist shows this history nicely formatted. You can also
2637 2637 do 'cd -<tab>' to see directory history conveniently.
2638 2638
2639 2639 Usage:
2640 2640
2641 2641 cd 'dir': changes to directory 'dir'.
2642 2642
2643 2643 cd -: changes to the last visited directory.
2644 2644
2645 2645 cd -<n>: changes to the n-th directory in the directory history.
2646 2646
2647 2647 cd --foo: change to directory that matches 'foo' in history
2648 2648
2649 2649 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
2650 2650 (note: cd <bookmark_name> is enough if there is no
2651 2651 directory <bookmark_name>, but a bookmark with the name exists.)
2652 2652 'cd -b <tab>' allows you to tab-complete bookmark names.
2653 2653
2654 2654 Options:
2655 2655
2656 2656 -q: quiet. Do not print the working directory after the cd command is
2657 2657 executed. By default IPython's cd command does print this directory,
2658 2658 since the default prompts do not display path information.
2659 2659
2660 2660 Note that !cd doesn't work for this purpose because the shell where
2661 2661 !command runs is immediately discarded after executing 'command'."""
2662 2662
2663 2663 parameter_s = parameter_s.strip()
2664 2664 #bkms = self.shell.persist.get("bookmarks",{})
2665 2665
2666 2666 oldcwd = os.getcwd()
2667 2667 numcd = re.match(r'(-)(\d+)$',parameter_s)
2668 2668 # jump in directory history by number
2669 2669 if numcd:
2670 2670 nn = int(numcd.group(2))
2671 2671 try:
2672 2672 ps = self.shell.user_ns['_dh'][nn]
2673 2673 except IndexError:
2674 2674 print 'The requested directory does not exist in history.'
2675 2675 return
2676 2676 else:
2677 2677 opts = {}
2678 2678 elif parameter_s.startswith('--'):
2679 2679 ps = None
2680 2680 fallback = None
2681 2681 pat = parameter_s[2:]
2682 2682 dh = self.shell.user_ns['_dh']
2683 2683 # first search only by basename (last component)
2684 2684 for ent in reversed(dh):
2685 2685 if pat in os.path.basename(ent) and os.path.isdir(ent):
2686 2686 ps = ent
2687 2687 break
2688 2688
2689 2689 if fallback is None and pat in ent and os.path.isdir(ent):
2690 2690 fallback = ent
2691 2691
2692 2692 # if we have no last part match, pick the first full path match
2693 2693 if ps is None:
2694 2694 ps = fallback
2695 2695
2696 2696 if ps is None:
2697 2697 print "No matching entry in directory history"
2698 2698 return
2699 2699 else:
2700 2700 opts = {}
2701 2701
2702 2702
2703 2703 else:
2704 2704 #turn all non-space-escaping backslashes to slashes,
2705 2705 # for c:\windows\directory\names\
2706 2706 parameter_s = re.sub(r'\\(?! )','/', parameter_s)
2707 2707 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
2708 2708 # jump to previous
2709 2709 if ps == '-':
2710 2710 try:
2711 2711 ps = self.shell.user_ns['_dh'][-2]
2712 2712 except IndexError:
2713 2713 raise UsageError('%cd -: No previous directory to change to.')
2714 2714 # jump to bookmark if needed
2715 2715 else:
2716 2716 if not os.path.isdir(ps) or opts.has_key('b'):
2717 2717 bkms = self.db.get('bookmarks', {})
2718 2718
2719 2719 if bkms.has_key(ps):
2720 2720 target = bkms[ps]
2721 2721 print '(bookmark:%s) -> %s' % (ps,target)
2722 2722 ps = target
2723 2723 else:
2724 2724 if opts.has_key('b'):
2725 2725 raise UsageError("Bookmark '%s' not found. "
2726 2726 "Use '%%bookmark -l' to see your bookmarks." % ps)
2727 2727
2728 2728 # at this point ps should point to the target dir
2729 2729 if ps:
2730 2730 try:
2731 2731 os.chdir(os.path.expanduser(ps))
2732 2732 if hasattr(self.shell, 'term_title') and self.shell.term_title:
2733 2733 set_term_title('IPython: ' + abbrev_cwd())
2734 2734 except OSError:
2735 2735 print sys.exc_info()[1]
2736 2736 else:
2737 2737 cwd = os.getcwd()
2738 2738 dhist = self.shell.user_ns['_dh']
2739 2739 if oldcwd != cwd:
2740 2740 dhist.append(cwd)
2741 2741 self.db['dhist'] = compress_dhist(dhist)[-100:]
2742 2742
2743 2743 else:
2744 2744 os.chdir(self.shell.home_dir)
2745 2745 if hasattr(self.shell, 'term_title') and self.shell.term_title:
2746 2746 set_term_title('IPython: ' + '~')
2747 2747 cwd = os.getcwd()
2748 2748 dhist = self.shell.user_ns['_dh']
2749 2749
2750 2750 if oldcwd != cwd:
2751 2751 dhist.append(cwd)
2752 2752 self.db['dhist'] = compress_dhist(dhist)[-100:]
2753 2753 if not 'q' in opts and self.shell.user_ns['_dh']:
2754 2754 print self.shell.user_ns['_dh'][-1]
2755 2755
2756 2756
2757 2757 def magic_env(self, parameter_s=''):
2758 2758 """List environment variables."""
2759 2759
2760 2760 return os.environ.data
2761 2761
2762 2762 def magic_pushd(self, parameter_s=''):
2763 2763 """Place the current dir on stack and change directory.
2764 2764
2765 2765 Usage:\\
2766 2766 %pushd ['dirname']
2767 2767 """
2768 2768
2769 2769 dir_s = self.shell.dir_stack
2770 2770 tgt = os.path.expanduser(parameter_s)
2771 2771 cwd = os.getcwd().replace(self.home_dir,'~')
2772 2772 if tgt:
2773 2773 self.magic_cd(parameter_s)
2774 2774 dir_s.insert(0,cwd)
2775 2775 return self.magic_dirs()
2776 2776
2777 2777 def magic_popd(self, parameter_s=''):
2778 2778 """Change to directory popped off the top of the stack.
2779 2779 """
2780 2780 if not self.shell.dir_stack:
2781 2781 raise UsageError("%popd on empty stack")
2782 2782 top = self.shell.dir_stack.pop(0)
2783 2783 self.magic_cd(top)
2784 2784 print "popd ->",top
2785 2785
2786 2786 def magic_dirs(self, parameter_s=''):
2787 2787 """Return the current directory stack."""
2788 2788
2789 2789 return self.shell.dir_stack
2790 2790
2791 2791 def magic_dhist(self, parameter_s=''):
2792 2792 """Print your history of visited directories.
2793 2793
2794 2794 %dhist -> print full history\\
2795 2795 %dhist n -> print last n entries only\\
2796 2796 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
2797 2797
2798 2798 This history is automatically maintained by the %cd command, and
2799 2799 always available as the global list variable _dh. You can use %cd -<n>
2800 2800 to go to directory number <n>.
2801 2801
2802 2802 Note that most of time, you should view directory history by entering
2803 2803 cd -<TAB>.
2804 2804
2805 2805 """
2806 2806
2807 2807 dh = self.shell.user_ns['_dh']
2808 2808 if parameter_s:
2809 2809 try:
2810 2810 args = map(int,parameter_s.split())
2811 2811 except:
2812 2812 self.arg_err(Magic.magic_dhist)
2813 2813 return
2814 2814 if len(args) == 1:
2815 2815 ini,fin = max(len(dh)-(args[0]),0),len(dh)
2816 2816 elif len(args) == 2:
2817 2817 ini,fin = args
2818 2818 else:
2819 2819 self.arg_err(Magic.magic_dhist)
2820 2820 return
2821 2821 else:
2822 2822 ini,fin = 0,len(dh)
2823 2823 nlprint(dh,
2824 2824 header = 'Directory history (kept in _dh)',
2825 2825 start=ini,stop=fin)
2826 2826
2827 2827 @testdec.skip_doctest
2828 2828 def magic_sc(self, parameter_s=''):
2829 2829 """Shell capture - execute a shell command and capture its output.
2830 2830
2831 2831 DEPRECATED. Suboptimal, retained for backwards compatibility.
2832 2832
2833 2833 You should use the form 'var = !command' instead. Example:
2834 2834
2835 2835 "%sc -l myfiles = ls ~" should now be written as
2836 2836
2837 2837 "myfiles = !ls ~"
2838 2838
2839 2839 myfiles.s, myfiles.l and myfiles.n still apply as documented
2840 2840 below.
2841 2841
2842 2842 --
2843 2843 %sc [options] varname=command
2844 2844
2845 2845 IPython will run the given command using commands.getoutput(), and
2846 2846 will then update the user's interactive namespace with a variable
2847 2847 called varname, containing the value of the call. Your command can
2848 2848 contain shell wildcards, pipes, etc.
2849 2849
2850 2850 The '=' sign in the syntax is mandatory, and the variable name you
2851 2851 supply must follow Python's standard conventions for valid names.
2852 2852
2853 2853 (A special format without variable name exists for internal use)
2854 2854
2855 2855 Options:
2856 2856
2857 2857 -l: list output. Split the output on newlines into a list before
2858 2858 assigning it to the given variable. By default the output is stored
2859 2859 as a single string.
2860 2860
2861 2861 -v: verbose. Print the contents of the variable.
2862 2862
2863 2863 In most cases you should not need to split as a list, because the
2864 2864 returned value is a special type of string which can automatically
2865 2865 provide its contents either as a list (split on newlines) or as a
2866 2866 space-separated string. These are convenient, respectively, either
2867 2867 for sequential processing or to be passed to a shell command.
2868 2868
2869 2869 For example:
2870 2870
2871 2871 # all-random
2872 2872
2873 2873 # Capture into variable a
2874 2874 In [1]: sc a=ls *py
2875 2875
2876 2876 # a is a string with embedded newlines
2877 2877 In [2]: a
2878 2878 Out[2]: 'setup.py\\nwin32_manual_post_install.py'
2879 2879
2880 2880 # which can be seen as a list:
2881 2881 In [3]: a.l
2882 2882 Out[3]: ['setup.py', 'win32_manual_post_install.py']
2883 2883
2884 2884 # or as a whitespace-separated string:
2885 2885 In [4]: a.s
2886 2886 Out[4]: 'setup.py win32_manual_post_install.py'
2887 2887
2888 2888 # a.s is useful to pass as a single command line:
2889 2889 In [5]: !wc -l $a.s
2890 2890 146 setup.py
2891 2891 130 win32_manual_post_install.py
2892 2892 276 total
2893 2893
2894 2894 # while the list form is useful to loop over:
2895 2895 In [6]: for f in a.l:
2896 2896 ...: !wc -l $f
2897 2897 ...:
2898 2898 146 setup.py
2899 2899 130 win32_manual_post_install.py
2900 2900
2901 2901 Similiarly, the lists returned by the -l option are also special, in
2902 2902 the sense that you can equally invoke the .s attribute on them to
2903 2903 automatically get a whitespace-separated string from their contents:
2904 2904
2905 2905 In [7]: sc -l b=ls *py
2906 2906
2907 2907 In [8]: b
2908 2908 Out[8]: ['setup.py', 'win32_manual_post_install.py']
2909 2909
2910 2910 In [9]: b.s
2911 2911 Out[9]: 'setup.py win32_manual_post_install.py'
2912 2912
2913 2913 In summary, both the lists and strings used for ouptut capture have
2914 2914 the following special attributes:
2915 2915
2916 2916 .l (or .list) : value as list.
2917 2917 .n (or .nlstr): value as newline-separated string.
2918 2918 .s (or .spstr): value as space-separated string.
2919 2919 """
2920 2920
2921 2921 opts,args = self.parse_options(parameter_s,'lv')
2922 2922 # Try to get a variable name and command to run
2923 2923 try:
2924 2924 # the variable name must be obtained from the parse_options
2925 2925 # output, which uses shlex.split to strip options out.
2926 2926 var,_ = args.split('=',1)
2927 2927 var = var.strip()
2928 2928 # But the the command has to be extracted from the original input
2929 2929 # parameter_s, not on what parse_options returns, to avoid the
2930 2930 # quote stripping which shlex.split performs on it.
2931 2931 _,cmd = parameter_s.split('=',1)
2932 2932 except ValueError:
2933 2933 var,cmd = '',''
2934 2934 # If all looks ok, proceed
2935 2935 out = self.shell.getoutput(cmd)
2936 2936 if opts.has_key('l'):
2937 2937 out = SList(out.split('\n'))
2938 2938 else:
2939 2939 out = LSString(out)
2940 2940 if opts.has_key('v'):
2941 2941 print '%s ==\n%s' % (var,pformat(out))
2942 2942 if var:
2943 2943 self.shell.user_ns.update({var:out})
2944 2944 else:
2945 2945 return out
2946 2946
2947 2947 def magic_sx(self, parameter_s=''):
2948 2948 """Shell execute - run a shell command and capture its output.
2949 2949
2950 2950 %sx command
2951 2951
2952 2952 IPython will run the given command using commands.getoutput(), and
2953 2953 return the result formatted as a list (split on '\\n'). Since the
2954 2954 output is _returned_, it will be stored in ipython's regular output
2955 2955 cache Out[N] and in the '_N' automatic variables.
2956 2956
2957 2957 Notes:
2958 2958
2959 2959 1) If an input line begins with '!!', then %sx is automatically
2960 2960 invoked. That is, while:
2961 2961 !ls
2962 2962 causes ipython to simply issue system('ls'), typing
2963 2963 !!ls
2964 2964 is a shorthand equivalent to:
2965 2965 %sx ls
2966 2966
2967 2967 2) %sx differs from %sc in that %sx automatically splits into a list,
2968 2968 like '%sc -l'. The reason for this is to make it as easy as possible
2969 2969 to process line-oriented shell output via further python commands.
2970 2970 %sc is meant to provide much finer control, but requires more
2971 2971 typing.
2972 2972
2973 2973 3) Just like %sc -l, this is a list with special attributes:
2974 2974
2975 2975 .l (or .list) : value as list.
2976 2976 .n (or .nlstr): value as newline-separated string.
2977 2977 .s (or .spstr): value as whitespace-separated string.
2978 2978
2979 2979 This is very useful when trying to use such lists as arguments to
2980 2980 system commands."""
2981 2981
2982 2982 if parameter_s:
2983 2983 out = self.shell.getoutput(parameter_s)
2984 2984 if out is not None:
2985 2985 return SList(out.splitlines())
2986 2986
2987 2987 def magic_r(self, parameter_s=''):
2988 2988 """Repeat previous input.
2989 2989
2990 2990 Note: Consider using the more powerfull %rep instead!
2991 2991
2992 2992 If given an argument, repeats the previous command which starts with
2993 2993 the same string, otherwise it just repeats the previous input.
2994 2994
2995 2995 Shell escaped commands (with ! as first character) are not recognized
2996 2996 by this system, only pure python code and magic commands.
2997 2997 """
2998 2998
2999 2999 start = parameter_s.strip()
3000 3000 esc_magic = ESC_MAGIC
3001 3001 # Identify magic commands even if automagic is on (which means
3002 3002 # the in-memory version is different from that typed by the user).
3003 3003 if self.shell.automagic:
3004 3004 start_magic = esc_magic+start
3005 3005 else:
3006 3006 start_magic = start
3007 3007 # Look through the input history in reverse
3008 3008 for n in range(len(self.shell.input_hist)-2,0,-1):
3009 3009 input = self.shell.input_hist[n]
3010 3010 # skip plain 'r' lines so we don't recurse to infinity
3011 3011 if input != '_ip.magic("r")\n' and \
3012 3012 (input.startswith(start) or input.startswith(start_magic)):
3013 3013 #print 'match',`input` # dbg
3014 3014 print 'Executing:',input,
3015 3015 self.shell.runlines(input)
3016 3016 return
3017 3017 print 'No previous input matching `%s` found.' % start
3018 3018
3019 3019
3020 3020 def magic_bookmark(self, parameter_s=''):
3021 3021 """Manage IPython's bookmark system.
3022 3022
3023 3023 %bookmark <name> - set bookmark to current dir
3024 3024 %bookmark <name> <dir> - set bookmark to <dir>
3025 3025 %bookmark -l - list all bookmarks
3026 3026 %bookmark -d <name> - remove bookmark
3027 3027 %bookmark -r - remove all bookmarks
3028 3028
3029 3029 You can later on access a bookmarked folder with:
3030 3030 %cd -b <name>
3031 3031 or simply '%cd <name>' if there is no directory called <name> AND
3032 3032 there is such a bookmark defined.
3033 3033
3034 3034 Your bookmarks persist through IPython sessions, but they are
3035 3035 associated with each profile."""
3036 3036
3037 3037 opts,args = self.parse_options(parameter_s,'drl',mode='list')
3038 3038 if len(args) > 2:
3039 3039 raise UsageError("%bookmark: too many arguments")
3040 3040
3041 3041 bkms = self.db.get('bookmarks',{})
3042 3042
3043 3043 if opts.has_key('d'):
3044 3044 try:
3045 3045 todel = args[0]
3046 3046 except IndexError:
3047 3047 raise UsageError(
3048 3048 "%bookmark -d: must provide a bookmark to delete")
3049 3049 else:
3050 3050 try:
3051 3051 del bkms[todel]
3052 3052 except KeyError:
3053 3053 raise UsageError(
3054 3054 "%%bookmark -d: Can't delete bookmark '%s'" % todel)
3055 3055
3056 3056 elif opts.has_key('r'):
3057 3057 bkms = {}
3058 3058 elif opts.has_key('l'):
3059 3059 bks = bkms.keys()
3060 3060 bks.sort()
3061 3061 if bks:
3062 3062 size = max(map(len,bks))
3063 3063 else:
3064 3064 size = 0
3065 3065 fmt = '%-'+str(size)+'s -> %s'
3066 3066 print 'Current bookmarks:'
3067 3067 for bk in bks:
3068 3068 print fmt % (bk,bkms[bk])
3069 3069 else:
3070 3070 if not args:
3071 3071 raise UsageError("%bookmark: You must specify the bookmark name")
3072 3072 elif len(args)==1:
3073 3073 bkms[args[0]] = os.getcwd()
3074 3074 elif len(args)==2:
3075 3075 bkms[args[0]] = args[1]
3076 3076 self.db['bookmarks'] = bkms
3077 3077
3078 3078 def magic_pycat(self, parameter_s=''):
3079 3079 """Show a syntax-highlighted file through a pager.
3080 3080
3081 3081 This magic is similar to the cat utility, but it will assume the file
3082 3082 to be Python source and will show it with syntax highlighting. """
3083 3083
3084 3084 try:
3085 3085 filename = get_py_filename(parameter_s)
3086 3086 cont = file_read(filename)
3087 3087 except IOError:
3088 3088 try:
3089 3089 cont = eval(parameter_s,self.user_ns)
3090 3090 except NameError:
3091 3091 cont = None
3092 3092 if cont is None:
3093 3093 print "Error: no such file or variable"
3094 3094 return
3095 3095
3096 3096 page.page(self.shell.pycolorize(cont))
3097 3097
3098 3098 def _rerun_pasted(self):
3099 3099 """ Rerun a previously pasted command.
3100 3100 """
3101 3101 b = self.user_ns.get('pasted_block', None)
3102 3102 if b is None:
3103 3103 raise UsageError('No previous pasted block available')
3104 3104 print "Re-executing '%s...' (%d chars)"% (b.split('\n',1)[0], len(b))
3105 3105 exec b in self.user_ns
3106 3106
3107 3107 def _get_pasted_lines(self, sentinel):
3108 3108 """ Yield pasted lines until the user enters the given sentinel value.
3109 3109 """
3110 3110 from IPython.core import interactiveshell
3111 3111 print "Pasting code; enter '%s' alone on the line to stop." % sentinel
3112 3112 while True:
3113 3113 l = interactiveshell.raw_input_original(':')
3114 3114 if l == sentinel:
3115 3115 return
3116 3116 else:
3117 3117 yield l
3118 3118
3119 3119 def _strip_pasted_lines_for_code(self, raw_lines):
3120 3120 """ Strip non-code parts of a sequence of lines to return a block of
3121 3121 code.
3122 3122 """
3123 3123 # Regular expressions that declare text we strip from the input:
3124 3124 strip_re = [r'^\s*In \[\d+\]:', # IPython input prompt
3125 3125 r'^\s*(\s?>)+', # Python input prompt
3126 3126 r'^\s*\.{3,}', # Continuation prompts
3127 3127 r'^\++',
3128 3128 ]
3129 3129
3130 3130 strip_from_start = map(re.compile,strip_re)
3131 3131
3132 3132 lines = []
3133 3133 for l in raw_lines:
3134 3134 for pat in strip_from_start:
3135 3135 l = pat.sub('',l)
3136 3136 lines.append(l)
3137 3137
3138 3138 block = "\n".join(lines) + '\n'
3139 3139 #print "block:\n",block
3140 3140 return block
3141 3141
3142 3142 def _execute_block(self, block, par):
3143 3143 """ Execute a block, or store it in a variable, per the user's request.
3144 3144 """
3145 3145 if not par:
3146 3146 b = textwrap.dedent(block)
3147 3147 self.user_ns['pasted_block'] = b
3148 3148 exec b in self.user_ns
3149 3149 else:
3150 3150 self.user_ns[par] = SList(block.splitlines())
3151 3151 print "Block assigned to '%s'" % par
3152 3152
3153 3153 def magic_cpaste(self, parameter_s=''):
3154 3154 """Allows you to paste & execute a pre-formatted code block from clipboard.
3155 3155
3156 3156 You must terminate the block with '--' (two minus-signs) alone on the
3157 3157 line. You can also provide your own sentinel with '%paste -s %%' ('%%'
3158 3158 is the new sentinel for this operation)
3159 3159
3160 3160 The block is dedented prior to execution to enable execution of method
3161 3161 definitions. '>' and '+' characters at the beginning of a line are
3162 3162 ignored, to allow pasting directly from e-mails, diff files and
3163 3163 doctests (the '...' continuation prompt is also stripped). The
3164 3164 executed block is also assigned to variable named 'pasted_block' for
3165 3165 later editing with '%edit pasted_block'.
3166 3166
3167 3167 You can also pass a variable name as an argument, e.g. '%cpaste foo'.
3168 3168 This assigns the pasted block to variable 'foo' as string, without
3169 3169 dedenting or executing it (preceding >>> and + is still stripped)
3170 3170
3171 3171 '%cpaste -r' re-executes the block previously entered by cpaste.
3172 3172
3173 3173 Do not be alarmed by garbled output on Windows (it's a readline bug).
3174 3174 Just press enter and type -- (and press enter again) and the block
3175 3175 will be what was just pasted.
3176 3176
3177 3177 IPython statements (magics, shell escapes) are not supported (yet).
3178 3178
3179 3179 See also
3180 3180 --------
3181 3181 paste: automatically pull code from clipboard.
3182 3182 """
3183 3183
3184 3184 opts,args = self.parse_options(parameter_s,'rs:',mode='string')
3185 3185 par = args.strip()
3186 3186 if opts.has_key('r'):
3187 3187 self._rerun_pasted()
3188 3188 return
3189 3189
3190 3190 sentinel = opts.get('s','--')
3191 3191
3192 3192 block = self._strip_pasted_lines_for_code(
3193 3193 self._get_pasted_lines(sentinel))
3194 3194
3195 3195 self._execute_block(block, par)
3196 3196
3197 3197 def magic_paste(self, parameter_s=''):
3198 3198 """Allows you to paste & execute a pre-formatted code block from clipboard.
3199 3199
3200 3200 The text is pulled directly from the clipboard without user
3201 3201 intervention and printed back on the screen before execution (unless
3202 3202 the -q flag is given to force quiet mode).
3203 3203
3204 3204 The block is dedented prior to execution to enable execution of method
3205 3205 definitions. '>' and '+' characters at the beginning of a line are
3206 3206 ignored, to allow pasting directly from e-mails, diff files and
3207 3207 doctests (the '...' continuation prompt is also stripped). The
3208 3208 executed block is also assigned to variable named 'pasted_block' for
3209 3209 later editing with '%edit pasted_block'.
3210 3210
3211 3211 You can also pass a variable name as an argument, e.g. '%paste foo'.
3212 3212 This assigns the pasted block to variable 'foo' as string, without
3213 3213 dedenting or executing it (preceding >>> and + is still stripped)
3214 3214
3215 3215 Options
3216 3216 -------
3217 3217
3218 3218 -r: re-executes the block previously entered by cpaste.
3219 3219
3220 3220 -q: quiet mode: do not echo the pasted text back to the terminal.
3221 3221
3222 3222 IPython statements (magics, shell escapes) are not supported (yet).
3223 3223
3224 3224 See also
3225 3225 --------
3226 3226 cpaste: manually paste code into terminal until you mark its end.
3227 3227 """
3228 3228 opts,args = self.parse_options(parameter_s,'rq',mode='string')
3229 3229 par = args.strip()
3230 3230 if opts.has_key('r'):
3231 3231 self._rerun_pasted()
3232 3232 return
3233 3233
3234 3234 text = self.shell.hooks.clipboard_get()
3235 3235 block = self._strip_pasted_lines_for_code(text.splitlines())
3236 3236
3237 3237 # By default, echo back to terminal unless quiet mode is requested
3238 3238 if not opts.has_key('q'):
3239 3239 write = self.shell.write
3240 3240 write(self.shell.pycolorize(block))
3241 3241 if not block.endswith('\n'):
3242 3242 write('\n')
3243 3243 write("## -- End pasted text --\n")
3244 3244
3245 3245 self._execute_block(block, par)
3246 3246
3247 3247 def magic_quickref(self,arg):
3248 3248 """ Show a quick reference sheet """
3249 3249 import IPython.core.usage
3250 3250 qr = IPython.core.usage.quick_reference + self.magic_magic('-brief')
3251 3251
3252 3252 page.page(qr)
3253 3253
3254 3254 def magic_doctest_mode(self,parameter_s=''):
3255 3255 """Toggle doctest mode on and off.
3256 3256
3257 This mode allows you to toggle the prompt behavior between normal
3258 IPython prompts and ones that are as similar to the default IPython
3259 interpreter as possible.
3260
3261 It also supports the pasting of code snippets that have leading '>>>'
3262 and '...' prompts in them. This means that you can paste doctests from
3263 files or docstrings (even if they have leading whitespace), and the
3264 code will execute correctly. You can then use '%history -tn' to see
3265 the translated history without line numbers; this will give you the
3257 This mode is intended to make IPython behave as much as possible like a
3258 plain Python shell, from the perspective of how its prompts, exceptions
3259 and output look. This makes it easy to copy and paste parts of a
3260 session into doctests. It does so by:
3261
3262 - Changing the prompts to the classic ``>>>`` ones.
3263 - Changing the exception reporting mode to 'Plain'.
3264 - Disabling pretty-printing of output.
3265
3266 Note that IPython also supports the pasting of code snippets that have
3267 leading '>>>' and '...' prompts in them. This means that you can paste
3268 doctests from files or docstrings (even if they have leading
3269 whitespace), and the code will execute correctly. You can then use
3270 '%history -t' to see the translated history; this will give you the
3266 3271 input after removal of all the leading prompts and whitespace, which
3267 3272 can be pasted back into an editor.
3268 3273
3269 3274 With these features, you can switch into this mode easily whenever you
3270 3275 need to do testing and changes to doctests, without having to leave
3271 3276 your existing IPython session.
3272 3277 """
3273 3278
3274 3279 from IPython.utils.ipstruct import Struct
3275 3280
3276 3281 # Shorthands
3277 3282 shell = self.shell
3278 3283 oc = shell.displayhook
3279 3284 meta = shell.meta
3280 3285 # dstore is a data store kept in the instance metadata bag to track any
3281 3286 # changes we make, so we can undo them later.
3282 3287 dstore = meta.setdefault('doctest_mode',Struct())
3283 3288 save_dstore = dstore.setdefault
3284 3289
3285 3290 # save a few values we'll need to recover later
3286 3291 mode = save_dstore('mode',False)
3287 3292 save_dstore('rc_pprint',shell.pprint)
3288 3293 save_dstore('xmode',shell.InteractiveTB.mode)
3289 3294 save_dstore('rc_separate_out',shell.separate_out)
3290 3295 save_dstore('rc_separate_out2',shell.separate_out2)
3291 3296 save_dstore('rc_prompts_pad_left',shell.prompts_pad_left)
3292 3297 save_dstore('rc_separate_in',shell.separate_in)
3293 3298
3294 3299 if mode == False:
3295 3300 # turn on
3296 3301 oc.prompt1.p_template = '>>> '
3297 3302 oc.prompt2.p_template = '... '
3298 3303 oc.prompt_out.p_template = ''
3299 3304
3300 3305 # Prompt separators like plain python
3301 3306 oc.input_sep = oc.prompt1.sep = ''
3302 3307 oc.output_sep = ''
3303 3308 oc.output_sep2 = ''
3304 3309
3305 3310 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3306 3311 oc.prompt_out.pad_left = False
3307 3312
3308 3313 shell.pprint = False
3309 3314
3310 3315 shell.magic_xmode('Plain')
3311
3312 3316 else:
3313 3317 # turn off
3314 3318 oc.prompt1.p_template = shell.prompt_in1
3315 3319 oc.prompt2.p_template = shell.prompt_in2
3316 3320 oc.prompt_out.p_template = shell.prompt_out
3317 3321
3318 3322 oc.input_sep = oc.prompt1.sep = dstore.rc_separate_in
3319 3323
3320 3324 oc.output_sep = dstore.rc_separate_out
3321 3325 oc.output_sep2 = dstore.rc_separate_out2
3322 3326
3323 3327 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3324 3328 oc.prompt_out.pad_left = dstore.rc_prompts_pad_left
3325 3329
3326 3330 shell.pprint = dstore.rc_pprint
3327 3331
3328 3332 shell.magic_xmode(dstore.xmode)
3329 3333
3330 3334 # Store new mode and inform
3331 3335 dstore.mode = bool(1-int(mode))
3332 print 'Doctest mode is:',
3333 print ['OFF','ON'][dstore.mode]
3336 mode_label = ['OFF','ON'][dstore.mode]
3337 print 'Doctest mode is:', mode_label
3334 3338
3335 3339 def magic_gui(self, parameter_s=''):
3336 3340 """Enable or disable IPython GUI event loop integration.
3337 3341
3338 3342 %gui [GUINAME]
3339 3343
3340 3344 This magic replaces IPython's threaded shells that were activated
3341 3345 using the (pylab/wthread/etc.) command line flags. GUI toolkits
3342 3346 can now be enabled, disabled and swtiched at runtime and keyboard
3343 3347 interrupts should work without any problems. The following toolkits
3344 3348 are supported: wxPython, PyQt4, PyGTK, and Tk::
3345 3349
3346 3350 %gui wx # enable wxPython event loop integration
3347 3351 %gui qt4|qt # enable PyQt4 event loop integration
3348 3352 %gui gtk # enable PyGTK event loop integration
3349 3353 %gui tk # enable Tk event loop integration
3350 3354 %gui # disable all event loop integration
3351 3355
3352 3356 WARNING: after any of these has been called you can simply create
3353 3357 an application object, but DO NOT start the event loop yourself, as
3354 3358 we have already handled that.
3355 3359 """
3356 3360 from IPython.lib.inputhook import enable_gui
3357 3361 opts, arg = self.parse_options(parameter_s='')
3358 3362 if arg=='': arg = None
3359 3363 return enable_gui(arg)
3360 3364
3361 3365 def magic_load_ext(self, module_str):
3362 3366 """Load an IPython extension by its module name."""
3363 3367 return self.extension_manager.load_extension(module_str)
3364 3368
3365 3369 def magic_unload_ext(self, module_str):
3366 3370 """Unload an IPython extension by its module name."""
3367 3371 self.extension_manager.unload_extension(module_str)
3368 3372
3369 3373 def magic_reload_ext(self, module_str):
3370 3374 """Reload an IPython extension by its module name."""
3371 3375 self.extension_manager.reload_extension(module_str)
3372 3376
3373 3377 @testdec.skip_doctest
3374 3378 def magic_install_profiles(self, s):
3375 3379 """Install the default IPython profiles into the .ipython dir.
3376 3380
3377 3381 If the default profiles have already been installed, they will not
3378 3382 be overwritten. You can force overwriting them by using the ``-o``
3379 3383 option::
3380 3384
3381 3385 In [1]: %install_profiles -o
3382 3386 """
3383 3387 if '-o' in s:
3384 3388 overwrite = True
3385 3389 else:
3386 3390 overwrite = False
3387 3391 from IPython.config import profile
3388 3392 profile_dir = os.path.split(profile.__file__)[0]
3389 3393 ipython_dir = self.ipython_dir
3390 3394 files = os.listdir(profile_dir)
3391 3395
3392 3396 to_install = []
3393 3397 for f in files:
3394 3398 if f.startswith('ipython_config'):
3395 3399 src = os.path.join(profile_dir, f)
3396 3400 dst = os.path.join(ipython_dir, f)
3397 3401 if (not os.path.isfile(dst)) or overwrite:
3398 3402 to_install.append((f, src, dst))
3399 3403 if len(to_install)>0:
3400 3404 print "Installing profiles to: ", ipython_dir
3401 3405 for (f, src, dst) in to_install:
3402 3406 shutil.copy(src, dst)
3403 3407 print " %s" % f
3404 3408
3405 3409 def magic_install_default_config(self, s):
3406 3410 """Install IPython's default config file into the .ipython dir.
3407 3411
3408 3412 If the default config file (:file:`ipython_config.py`) is already
3409 3413 installed, it will not be overwritten. You can force overwriting
3410 3414 by using the ``-o`` option::
3411 3415
3412 3416 In [1]: %install_default_config
3413 3417 """
3414 3418 if '-o' in s:
3415 3419 overwrite = True
3416 3420 else:
3417 3421 overwrite = False
3418 3422 from IPython.config import default
3419 3423 config_dir = os.path.split(default.__file__)[0]
3420 3424 ipython_dir = self.ipython_dir
3421 3425 default_config_file_name = 'ipython_config.py'
3422 3426 src = os.path.join(config_dir, default_config_file_name)
3423 3427 dst = os.path.join(ipython_dir, default_config_file_name)
3424 3428 if (not os.path.isfile(dst)) or overwrite:
3425 3429 shutil.copy(src, dst)
3426 3430 print "Installing default config file: %s" % dst
3427 3431
3428 3432 # Pylab support: simple wrappers that activate pylab, load gui input
3429 3433 # handling and modify slightly %run
3430 3434
3431 3435 @testdec.skip_doctest
3432 3436 def _pylab_magic_run(self, parameter_s=''):
3433 3437 Magic.magic_run(self, parameter_s,
3434 3438 runner=mpl_runner(self.shell.safe_execfile))
3435 3439
3436 3440 _pylab_magic_run.__doc__ = magic_run.__doc__
3437 3441
3438 3442 @testdec.skip_doctest
3439 3443 def magic_pylab(self, s):
3440 3444 """Load numpy and matplotlib to work interactively.
3441 3445
3442 3446 %pylab [GUINAME]
3443 3447
3444 3448 This function lets you activate pylab (matplotlib, numpy and
3445 3449 interactive support) at any point during an IPython session.
3446 3450
3447 3451 It will import at the top level numpy as np, pyplot as plt, matplotlib,
3448 3452 pylab and mlab, as well as all names from numpy and pylab.
3449 3453
3450 3454 Parameters
3451 3455 ----------
3452 3456 guiname : optional
3453 3457 One of the valid arguments to the %gui magic ('qt', 'wx', 'gtk' or
3454 3458 'tk'). If given, the corresponding Matplotlib backend is used,
3455 3459 otherwise matplotlib's default (which you can override in your
3456 3460 matplotlib config file) is used.
3457 3461
3458 3462 Examples
3459 3463 --------
3460 3464 In this case, where the MPL default is TkAgg:
3461 3465 In [2]: %pylab
3462 3466
3463 3467 Welcome to pylab, a matplotlib-based Python environment.
3464 3468 Backend in use: TkAgg
3465 3469 For more information, type 'help(pylab)'.
3466 3470
3467 3471 But you can explicitly request a different backend:
3468 3472 In [3]: %pylab qt
3469 3473
3470 3474 Welcome to pylab, a matplotlib-based Python environment.
3471 3475 Backend in use: Qt4Agg
3472 3476 For more information, type 'help(pylab)'.
3473 3477 """
3474 3478 self.shell.enable_pylab(s)
3475 3479
3476 3480 def magic_tb(self, s):
3477 3481 """Print the last traceback with the currently active exception mode.
3478 3482
3479 3483 See %xmode for changing exception reporting modes."""
3480 3484 self.shell.showtraceback()
3481 3485
3482 3486 # end Magic
@@ -1,426 +1,485 b''
1 1 """A ZMQ-based subclass of InteractiveShell.
2 2
3 3 This code is meant to ease the refactoring of the base InteractiveShell into
4 4 something with a cleaner architecture for 2-process use, without actually
5 5 breaking InteractiveShell itself. So we're doing something a bit ugly, where
6 6 we subclass and override what we want to fix. Once this is working well, we
7 7 can go back to the base class and refactor the code for a cleaner inheritance
8 8 implementation that doesn't rely on so much monkeypatching.
9 9
10 10 But this lets us maintain a fully working IPython as we develop the new
11 11 machinery. This should thus be thought of as scaffolding.
12 12 """
13 13 #-----------------------------------------------------------------------------
14 14 # Imports
15 15 #-----------------------------------------------------------------------------
16 16 from __future__ import print_function
17 17
18 18 # Stdlib
19 19 import inspect
20 20 import os
21 21 import re
22 22
23 23 # Our own
24 24 from IPython.core.interactiveshell import (
25 25 InteractiveShell, InteractiveShellABC
26 26 )
27 27 from IPython.core.displayhook import DisplayHook
28 28 from IPython.core.macro import Macro
29 29 from IPython.utils.path import get_py_filename
30 30 from IPython.utils.text import StringTypes
31 31 from IPython.utils.traitlets import Instance, Type, Dict
32 32 from IPython.utils.warn import warn
33 33 from IPython.zmq.session import extract_header
34 34 from IPython.core.payloadpage import install_payload_page
35 35 from session import Session
36 36
37 37 #-----------------------------------------------------------------------------
38 38 # Globals and side-effects
39 39 #-----------------------------------------------------------------------------
40 40
41 41 # Install the payload version of page.
42 42 install_payload_page()
43 43
44 44 #-----------------------------------------------------------------------------
45 45 # Functions and classes
46 46 #-----------------------------------------------------------------------------
47 47
48 48 class ZMQDisplayHook(DisplayHook):
49 49
50 50 session = Instance(Session)
51 51 pub_socket = Instance('zmq.Socket')
52 52 parent_header = Dict({})
53 53
54 54 def set_parent(self, parent):
55 55 """Set the parent for outbound messages."""
56 56 self.parent_header = extract_header(parent)
57 57
58 58 def start_displayhook(self):
59 59 self.msg = self.session.msg(u'pyout', {}, parent=self.parent_header)
60 60
61 61 def write_output_prompt(self):
62 62 """Write the output prompt."""
63 63 if self.do_full_cache:
64 64 self.msg['content']['execution_count'] = self.prompt_count
65 65
66 66 def write_result_repr(self, result_repr):
67 67 self.msg['content']['data'] = result_repr
68 68
69 69 def finish_displayhook(self):
70 70 """Finish up all displayhook activities."""
71 71 self.pub_socket.send_json(self.msg)
72 72 self.msg = None
73 73
74 74
75 75 class ZMQInteractiveShell(InteractiveShell):
76 76 """A subclass of InteractiveShell for ZMQ."""
77 77
78 78 displayhook_class = Type(ZMQDisplayHook)
79 79
80 80 def init_io(self):
81 81 # This will just use sys.stdout and sys.stderr. If you want to
82 82 # override sys.stdout and sys.stderr themselves, you need to do that
83 83 # *before* instantiating this class, because Term holds onto
84 84 # references to the underlying streams.
85 85 import IPython.utils.io
86 86 Term = IPython.utils.io.IOTerm()
87 87 IPython.utils.io.Term = Term
88 88
89 def magic_doctest_mode(self,parameter_s=''):
90 """Toggle doctest mode on and off.
91
92 This mode is intended to make IPython behave as much as possible like a
93 plain Python shell, from the perspective of how its prompts, exceptions
94 and output look. This makes it easy to copy and paste parts of a
95 session into doctests. It does so by:
96
97 - Changing the prompts to the classic ``>>>`` ones.
98 - Changing the exception reporting mode to 'Plain'.
99 - Disabling pretty-printing of output.
100
101 Note that IPython also supports the pasting of code snippets that have
102 leading '>>>' and '...' prompts in them. This means that you can paste
103 doctests from files or docstrings (even if they have leading
104 whitespace), and the code will execute correctly. You can then use
105 '%history -t' to see the translated history; this will give you the
106 input after removal of all the leading prompts and whitespace, which
107 can be pasted back into an editor.
108
109 With these features, you can switch into this mode easily whenever you
110 need to do testing and changes to doctests, without having to leave
111 your existing IPython session.
112 """
113
114 from IPython.utils.ipstruct import Struct
115
116 # Shorthands
117 shell = self.shell
118 # dstore is a data store kept in the instance metadata bag to track any
119 # changes we make, so we can undo them later.
120 dstore = shell.meta.setdefault('doctest_mode', Struct())
121 save_dstore = dstore.setdefault
122
123 # save a few values we'll need to recover later
124 mode = save_dstore('mode', False)
125 save_dstore('rc_pprint', shell.pprint)
126 save_dstore('xmode', shell.InteractiveTB.mode)
127
128 if mode == False:
129 # turn on
130 shell.pprint = False
131 shell.magic_xmode('Plain')
132 else:
133 # turn off
134 shell.pprint = dstore.rc_pprint
135 shell.magic_xmode(dstore.xmode)
136
137 # Store new mode and inform on console
138 dstore.mode = bool(1-int(mode))
139 mode_label = ['OFF','ON'][dstore.mode]
140 print('Doctest mode is:', mode_label)
141
142 # Send the payload back so that clients can modify their prompt display
143 payload = dict(
144 source='IPython.zmq.zmqshell.ZMQInteractiveShell.magic_doctest_mode',
145 mode=dstore.mode)
146 self.payload_manager.write_payload(payload)
147
89 148 def magic_edit(self,parameter_s='',last_call=['','']):
90 149 """Bring up an editor and execute the resulting code.
91 150
92 151 Usage:
93 152 %edit [options] [args]
94 153
95 154 %edit runs IPython's editor hook. The default version of this hook is
96 155 set to call the __IPYTHON__.rc.editor command. This is read from your
97 156 environment variable $EDITOR. If this isn't found, it will default to
98 157 vi under Linux/Unix and to notepad under Windows. See the end of this
99 158 docstring for how to change the editor hook.
100 159
101 160 You can also set the value of this editor via the command line option
102 161 '-editor' or in your ipythonrc file. This is useful if you wish to use
103 162 specifically for IPython an editor different from your typical default
104 163 (and for Windows users who typically don't set environment variables).
105 164
106 165 This command allows you to conveniently edit multi-line code right in
107 166 your IPython session.
108 167
109 168 If called without arguments, %edit opens up an empty editor with a
110 169 temporary file and will execute the contents of this file when you
111 170 close it (don't forget to save it!).
112 171
113 172
114 173 Options:
115 174
116 175 -n <number>: open the editor at a specified line number. By default,
117 176 the IPython editor hook uses the unix syntax 'editor +N filename', but
118 177 you can configure this by providing your own modified hook if your
119 178 favorite editor supports line-number specifications with a different
120 179 syntax.
121 180
122 181 -p: this will call the editor with the same data as the previous time
123 182 it was used, regardless of how long ago (in your current session) it
124 183 was.
125 184
126 185 -r: use 'raw' input. This option only applies to input taken from the
127 186 user's history. By default, the 'processed' history is used, so that
128 187 magics are loaded in their transformed version to valid Python. If
129 188 this option is given, the raw input as typed as the command line is
130 189 used instead. When you exit the editor, it will be executed by
131 190 IPython's own processor.
132 191
133 192 -x: do not execute the edited code immediately upon exit. This is
134 193 mainly useful if you are editing programs which need to be called with
135 194 command line arguments, which you can then do using %run.
136 195
137 196
138 197 Arguments:
139 198
140 199 If arguments are given, the following possibilites exist:
141 200
142 201 - The arguments are numbers or pairs of colon-separated numbers (like
143 202 1 4:8 9). These are interpreted as lines of previous input to be
144 203 loaded into the editor. The syntax is the same of the %macro command.
145 204
146 205 - If the argument doesn't start with a number, it is evaluated as a
147 206 variable and its contents loaded into the editor. You can thus edit
148 207 any string which contains python code (including the result of
149 208 previous edits).
150 209
151 210 - If the argument is the name of an object (other than a string),
152 211 IPython will try to locate the file where it was defined and open the
153 212 editor at the point where it is defined. You can use `%edit function`
154 213 to load an editor exactly at the point where 'function' is defined,
155 214 edit it and have the file be executed automatically.
156 215
157 216 If the object is a macro (see %macro for details), this opens up your
158 217 specified editor with a temporary file containing the macro's data.
159 218 Upon exit, the macro is reloaded with the contents of the file.
160 219
161 220 Note: opening at an exact line is only supported under Unix, and some
162 221 editors (like kedit and gedit up to Gnome 2.8) do not understand the
163 222 '+NUMBER' parameter necessary for this feature. Good editors like
164 223 (X)Emacs, vi, jed, pico and joe all do.
165 224
166 225 - If the argument is not found as a variable, IPython will look for a
167 226 file with that name (adding .py if necessary) and load it into the
168 227 editor. It will execute its contents with execfile() when you exit,
169 228 loading any code in the file into your interactive namespace.
170 229
171 230 After executing your code, %edit will return as output the code you
172 231 typed in the editor (except when it was an existing file). This way
173 232 you can reload the code in further invocations of %edit as a variable,
174 233 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
175 234 the output.
176 235
177 236 Note that %edit is also available through the alias %ed.
178 237
179 238 This is an example of creating a simple function inside the editor and
180 239 then modifying it. First, start up the editor:
181 240
182 241 In [1]: ed
183 242 Editing... done. Executing edited code...
184 243 Out[1]: 'def foo():n print "foo() was defined in an editing session"n'
185 244
186 245 We can then call the function foo():
187 246
188 247 In [2]: foo()
189 248 foo() was defined in an editing session
190 249
191 250 Now we edit foo. IPython automatically loads the editor with the
192 251 (temporary) file where foo() was previously defined:
193 252
194 253 In [3]: ed foo
195 254 Editing... done. Executing edited code...
196 255
197 256 And if we call foo() again we get the modified version:
198 257
199 258 In [4]: foo()
200 259 foo() has now been changed!
201 260
202 261 Here is an example of how to edit a code snippet successive
203 262 times. First we call the editor:
204 263
205 264 In [5]: ed
206 265 Editing... done. Executing edited code...
207 266 hello
208 267 Out[5]: "print 'hello'n"
209 268
210 269 Now we call it again with the previous output (stored in _):
211 270
212 271 In [6]: ed _
213 272 Editing... done. Executing edited code...
214 273 hello world
215 274 Out[6]: "print 'hello world'n"
216 275
217 276 Now we call it with the output #8 (stored in _8, also as Out[8]):
218 277
219 278 In [7]: ed _8
220 279 Editing... done. Executing edited code...
221 280 hello again
222 281 Out[7]: "print 'hello again'n"
223 282
224 283
225 284 Changing the default editor hook:
226 285
227 286 If you wish to write your own editor hook, you can put it in a
228 287 configuration file which you load at startup time. The default hook
229 288 is defined in the IPython.core.hooks module, and you can use that as a
230 289 starting example for further modifications. That file also has
231 290 general instructions on how to set a new hook for use once you've
232 291 defined it."""
233 292
234 293 # FIXME: This function has become a convoluted mess. It needs a
235 294 # ground-up rewrite with clean, simple logic.
236 295
237 296 def make_filename(arg):
238 297 "Make a filename from the given args"
239 298 try:
240 299 filename = get_py_filename(arg)
241 300 except IOError:
242 301 if args.endswith('.py'):
243 302 filename = arg
244 303 else:
245 304 filename = None
246 305 return filename
247 306
248 307 # custom exceptions
249 308 class DataIsObject(Exception): pass
250 309
251 310 opts,args = self.parse_options(parameter_s,'prn:')
252 311 # Set a few locals from the options for convenience:
253 312 opts_p = opts.has_key('p')
254 313 opts_r = opts.has_key('r')
255 314
256 315 # Default line number value
257 316 lineno = opts.get('n',None)
258 317 if lineno is not None:
259 318 try:
260 319 lineno = int(lineno)
261 320 except:
262 321 warn("The -n argument must be an integer.")
263 322 return
264 323
265 324 if opts_p:
266 325 args = '_%s' % last_call[0]
267 326 if not self.shell.user_ns.has_key(args):
268 327 args = last_call[1]
269 328
270 329 # use last_call to remember the state of the previous call, but don't
271 330 # let it be clobbered by successive '-p' calls.
272 331 try:
273 332 last_call[0] = self.shell.displayhook.prompt_count
274 333 if not opts_p:
275 334 last_call[1] = parameter_s
276 335 except:
277 336 pass
278 337
279 338 # by default this is done with temp files, except when the given
280 339 # arg is a filename
281 340 use_temp = 1
282 341
283 342 if re.match(r'\d',args):
284 343 # Mode where user specifies ranges of lines, like in %macro.
285 344 # This means that you can't edit files whose names begin with
286 345 # numbers this way. Tough.
287 346 ranges = args.split()
288 347 data = ''.join(self.extract_input_slices(ranges,opts_r))
289 348 elif args.endswith('.py'):
290 349 filename = make_filename(args)
291 350 data = ''
292 351 use_temp = 0
293 352 elif args:
294 353 try:
295 354 # Load the parameter given as a variable. If not a string,
296 355 # process it as an object instead (below)
297 356
298 357 #print '*** args',args,'type',type(args) # dbg
299 358 data = eval(args,self.shell.user_ns)
300 359 if not type(data) in StringTypes:
301 360 raise DataIsObject
302 361
303 362 except (NameError,SyntaxError):
304 363 # given argument is not a variable, try as a filename
305 364 filename = make_filename(args)
306 365 if filename is None:
307 366 warn("Argument given (%s) can't be found as a variable "
308 367 "or as a filename." % args)
309 368 return
310 369
311 370 data = ''
312 371 use_temp = 0
313 372 except DataIsObject:
314 373
315 374 # macros have a special edit function
316 375 if isinstance(data,Macro):
317 376 self._edit_macro(args,data)
318 377 return
319 378
320 379 # For objects, try to edit the file where they are defined
321 380 try:
322 381 filename = inspect.getabsfile(data)
323 382 if 'fakemodule' in filename.lower() and inspect.isclass(data):
324 383 # class created by %edit? Try to find source
325 384 # by looking for method definitions instead, the
326 385 # __module__ in those classes is FakeModule.
327 386 attrs = [getattr(data, aname) for aname in dir(data)]
328 387 for attr in attrs:
329 388 if not inspect.ismethod(attr):
330 389 continue
331 390 filename = inspect.getabsfile(attr)
332 391 if filename and 'fakemodule' not in filename.lower():
333 392 # change the attribute to be the edit target instead
334 393 data = attr
335 394 break
336 395
337 396 datafile = 1
338 397 except TypeError:
339 398 filename = make_filename(args)
340 399 datafile = 1
341 400 warn('Could not find file where `%s` is defined.\n'
342 401 'Opening a file named `%s`' % (args,filename))
343 402 # Now, make sure we can actually read the source (if it was in
344 403 # a temp file it's gone by now).
345 404 if datafile:
346 405 try:
347 406 if lineno is None:
348 407 lineno = inspect.getsourcelines(data)[1]
349 408 except IOError:
350 409 filename = make_filename(args)
351 410 if filename is None:
352 411 warn('The file `%s` where `%s` was defined cannot '
353 412 'be read.' % (filename,data))
354 413 return
355 414 use_temp = 0
356 415 else:
357 416 data = ''
358 417
359 418 if use_temp:
360 419 filename = self.shell.mktempfile(data)
361 420 print('IPython will make a temporary file named:', filename)
362 421
363 422 # Make sure we send to the client an absolute path, in case the working
364 423 # directory of client and kernel don't match
365 424 filename = os.path.abspath(filename)
366 425
367 426 payload = {
368 427 'source' : 'IPython.zmq.zmqshell.ZMQInteractiveShell.edit_magic',
369 428 'filename' : filename,
370 429 'line_number' : lineno
371 430 }
372 431 self.payload_manager.write_payload(payload)
373 432
374 433 def magic_gui(self, *args, **kwargs):
375 434 raise NotImplementedError('GUI support must be enabled in command line options.')
376 435
377 436 def magic_pylab(self, *args, **kwargs):
378 437 raise NotImplementedError('pylab support must be enabled in commandl in options.')
379 438
380 439 def auto_rewrite_input(self, cmd):
381 440 """Called to show the auto-rewritten input for autocall and friends.
382 441
383 442 FIXME: this payload is currently not correctly processed by the
384 443 frontend.
385 444 """
386 445 new = self.displayhook.prompt1.auto_rewrite() + cmd
387 446 payload = dict(
388 447 source='IPython.zmq.zmqshell.ZMQInteractiveShell.auto_rewrite_input',
389 448 transformed_input=new,
390 449 )
391 450 self.payload_manager.write_payload(payload)
392 451
393 452 def ask_exit(self):
394 453 """Engage the exit actions."""
395 454 payload = dict(
396 455 source='IPython.zmq.zmqshell.ZMQInteractiveShell.ask_exit',
397 456 exit=True,
398 457 )
399 458 self.payload_manager.write_payload(payload)
400 459
401 460 def _showtraceback(self, etype, evalue, stb):
402 461
403 462 exc_content = {
404 463 u'traceback' : stb,
405 464 u'ename' : unicode(etype.__name__),
406 465 u'evalue' : unicode(evalue)
407 466 }
408 467
409 468 dh = self.displayhook
410 469 exc_msg = dh.session.msg(u'pyerr', exc_content, dh.parent_header)
411 470 # Send exception info over pub socket for other clients than the caller
412 471 # to pick up
413 472 dh.pub_socket.send_json(exc_msg)
414 473
415 474 # FIXME - Hack: store exception info in shell object. Right now, the
416 475 # caller is reading this info after the fact, we need to fix this logic
417 476 # to remove this hack. Even uglier, we need to store the error status
418 477 # here, because in the main loop, the logic that sets it is being
419 478 # skipped because runlines swallows the exceptions.
420 479 exc_content[u'status'] = u'error'
421 480 self._reply_content = exc_content
422 481 # /FIXME
423 482
424 483 return exc_content
425 484
426 485 InteractiveShellABC.register(ZMQInteractiveShell)
General Comments 0
You need to be logged in to leave comments. Login now