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