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