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