##// END OF EJS Templates
add --no-display flag to %%capture...
Paul Ivanov -
Show More
@@ -1,1227 +1,1231 b''
1 1 # -*- coding: utf-8 -*-
2 2 """Implementation of execution-related magic functions.
3 3 """
4 4 #-----------------------------------------------------------------------------
5 5 # Copyright (c) 2012 The IPython Development Team.
6 6 #
7 7 # Distributed under the terms of the Modified BSD License.
8 8 #
9 9 # The full license is in the file COPYING.txt, distributed with this software.
10 10 #-----------------------------------------------------------------------------
11 11
12 12 #-----------------------------------------------------------------------------
13 13 # Imports
14 14 #-----------------------------------------------------------------------------
15 15
16 16 # Stdlib
17 17 import __builtin__ as builtin_mod
18 18 import ast
19 19 import bdb
20 20 import os
21 21 import sys
22 22 import time
23 23 from StringIO import StringIO
24 24
25 25 # cProfile was added in Python2.5
26 26 try:
27 27 import cProfile as profile
28 28 import pstats
29 29 except ImportError:
30 30 # profile isn't bundled by default in Debian for license reasons
31 31 try:
32 32 import profile, pstats
33 33 except ImportError:
34 34 profile = pstats = None
35 35
36 36 # Our own packages
37 37 from IPython.core import debugger, oinspect
38 38 from IPython.core import magic_arguments
39 39 from IPython.core import page
40 40 from IPython.core.error import UsageError
41 41 from IPython.core.macro import Macro
42 42 from IPython.core.magic import (Magics, magics_class, line_magic, cell_magic,
43 43 line_cell_magic, on_off, needs_local_scope)
44 44 from IPython.testing.skipdoctest import skip_doctest
45 45 from IPython.utils import py3compat
46 46 from IPython.utils.contexts import preserve_keys
47 47 from IPython.utils.io import capture_output
48 48 from IPython.utils.ipstruct import Struct
49 49 from IPython.utils.module_paths import find_mod
50 50 from IPython.utils.path import get_py_filename, unquote_filename, shellglob
51 51 from IPython.utils.timing import clock, clock2
52 52 from IPython.utils.warn import warn, error
53 53
54 54
55 55 #-----------------------------------------------------------------------------
56 56 # Magic implementation classes
57 57 #-----------------------------------------------------------------------------
58 58
59 59 @magics_class
60 60 class ExecutionMagics(Magics):
61 61 """Magics related to code execution, debugging, profiling, etc.
62 62
63 63 """
64 64
65 65 def __init__(self, shell):
66 66 super(ExecutionMagics, self).__init__(shell)
67 67 if profile is None:
68 68 self.prun = self.profile_missing_notice
69 69 # Default execution function used to actually run user code.
70 70 self.default_runner = None
71 71
72 72 def profile_missing_notice(self, *args, **kwargs):
73 73 error("""\
74 74 The profile module could not be found. It has been removed from the standard
75 75 python packages because of its non-free license. To use profiling, install the
76 76 python-profiler package from non-free.""")
77 77
78 78 @skip_doctest
79 79 @line_cell_magic
80 80 def prun(self, parameter_s='', cell=None):
81 81
82 82 """Run a statement through the python code profiler.
83 83
84 84 Usage, in line mode:
85 85 %prun [options] statement
86 86
87 87 Usage, in cell mode:
88 88 %%prun [options] [statement]
89 89 code...
90 90 code...
91 91
92 92 In cell mode, the additional code lines are appended to the (possibly
93 93 empty) statement in the first line. Cell mode allows you to easily
94 94 profile multiline blocks without having to put them in a separate
95 95 function.
96 96
97 97 The given statement (which doesn't require quote marks) is run via the
98 98 python profiler in a manner similar to the profile.run() function.
99 99 Namespaces are internally managed to work correctly; profile.run
100 100 cannot be used in IPython because it makes certain assumptions about
101 101 namespaces which do not hold under IPython.
102 102
103 103 Options:
104 104
105 105 -l <limit>: you can place restrictions on what or how much of the
106 106 profile gets printed. The limit value can be:
107 107
108 108 * A string: only information for function names containing this string
109 109 is printed.
110 110
111 111 * An integer: only these many lines are printed.
112 112
113 113 * A float (between 0 and 1): this fraction of the report is printed
114 114 (for example, use a limit of 0.4 to see the topmost 40% only).
115 115
116 116 You can combine several limits with repeated use of the option. For
117 117 example, '-l __init__ -l 5' will print only the topmost 5 lines of
118 118 information about class constructors.
119 119
120 120 -r: return the pstats.Stats object generated by the profiling. This
121 121 object has all the information about the profile in it, and you can
122 122 later use it for further analysis or in other functions.
123 123
124 124 -s <key>: sort profile by given key. You can provide more than one key
125 125 by using the option several times: '-s key1 -s key2 -s key3...'. The
126 126 default sorting key is 'time'.
127 127
128 128 The following is copied verbatim from the profile documentation
129 129 referenced below:
130 130
131 131 When more than one key is provided, additional keys are used as
132 132 secondary criteria when the there is equality in all keys selected
133 133 before them.
134 134
135 135 Abbreviations can be used for any key names, as long as the
136 136 abbreviation is unambiguous. The following are the keys currently
137 137 defined:
138 138
139 139 Valid Arg Meaning
140 140 "calls" call count
141 141 "cumulative" cumulative time
142 142 "file" file name
143 143 "module" file name
144 144 "pcalls" primitive call count
145 145 "line" line number
146 146 "name" function name
147 147 "nfl" name/file/line
148 148 "stdname" standard name
149 149 "time" internal time
150 150
151 151 Note that all sorts on statistics are in descending order (placing
152 152 most time consuming items first), where as name, file, and line number
153 153 searches are in ascending order (i.e., alphabetical). The subtle
154 154 distinction between "nfl" and "stdname" is that the standard name is a
155 155 sort of the name as printed, which means that the embedded line
156 156 numbers get compared in an odd way. For example, lines 3, 20, and 40
157 157 would (if the file names were the same) appear in the string order
158 158 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
159 159 line numbers. In fact, sort_stats("nfl") is the same as
160 160 sort_stats("name", "file", "line").
161 161
162 162 -T <filename>: save profile results as shown on screen to a text
163 163 file. The profile is still shown on screen.
164 164
165 165 -D <filename>: save (via dump_stats) profile statistics to given
166 166 filename. This data is in a format understood by the pstats module, and
167 167 is generated by a call to the dump_stats() method of profile
168 168 objects. The profile is still shown on screen.
169 169
170 170 -q: suppress output to the pager. Best used with -T and/or -D above.
171 171
172 172 If you want to run complete programs under the profiler's control, use
173 173 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
174 174 contains profiler specific options as described here.
175 175
176 176 You can read the complete documentation for the profile module with::
177 177
178 178 In [1]: import profile; profile.help()
179 179 """
180 180 opts, arg_str = self.parse_options(parameter_s, 'D:l:rs:T:q',
181 181 list_all=True, posix=False)
182 182 if cell is not None:
183 183 arg_str += '\n' + cell
184 184 arg_str = self.shell.input_splitter.transform_cell(arg_str)
185 185 return self._run_with_profiler(arg_str, opts, self.shell.user_ns)
186 186
187 187 def _run_with_profiler(self, code, opts, namespace):
188 188 """
189 189 Run `code` with profiler. Used by ``%prun`` and ``%run -p``.
190 190
191 191 Parameters
192 192 ----------
193 193 code : str
194 194 Code to be executed.
195 195 opts : Struct
196 196 Options parsed by `self.parse_options`.
197 197 namespace : dict
198 198 A dictionary for Python namespace (e.g., `self.shell.user_ns`).
199 199
200 200 """
201 201
202 202 # Fill default values for unspecified options:
203 203 opts.merge(Struct(D=[''], l=[], s=['time'], T=['']))
204 204
205 205 prof = profile.Profile()
206 206 try:
207 207 prof = prof.runctx(code, namespace, namespace)
208 208 sys_exit = ''
209 209 except SystemExit:
210 210 sys_exit = """*** SystemExit exception caught in code being profiled."""
211 211
212 212 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
213 213
214 214 lims = opts.l
215 215 if lims:
216 216 lims = [] # rebuild lims with ints/floats/strings
217 217 for lim in opts.l:
218 218 try:
219 219 lims.append(int(lim))
220 220 except ValueError:
221 221 try:
222 222 lims.append(float(lim))
223 223 except ValueError:
224 224 lims.append(lim)
225 225
226 226 # Trap output.
227 227 stdout_trap = StringIO()
228 228 stats_stream = stats.stream
229 229 try:
230 230 stats.stream = stdout_trap
231 231 stats.print_stats(*lims)
232 232 finally:
233 233 stats.stream = stats_stream
234 234
235 235 output = stdout_trap.getvalue()
236 236 output = output.rstrip()
237 237
238 238 if 'q' not in opts:
239 239 page.page(output)
240 240 print sys_exit,
241 241
242 242 dump_file = opts.D[0]
243 243 text_file = opts.T[0]
244 244 if dump_file:
245 245 dump_file = unquote_filename(dump_file)
246 246 prof.dump_stats(dump_file)
247 247 print '\n*** Profile stats marshalled to file',\
248 248 repr(dump_file)+'.',sys_exit
249 249 if text_file:
250 250 text_file = unquote_filename(text_file)
251 251 pfile = open(text_file,'w')
252 252 pfile.write(output)
253 253 pfile.close()
254 254 print '\n*** Profile printout saved to text file',\
255 255 repr(text_file)+'.',sys_exit
256 256
257 257 if 'r' in opts:
258 258 return stats
259 259 else:
260 260 return None
261 261
262 262 @line_magic
263 263 def pdb(self, parameter_s=''):
264 264 """Control the automatic calling of the pdb interactive debugger.
265 265
266 266 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
267 267 argument it works as a toggle.
268 268
269 269 When an exception is triggered, IPython can optionally call the
270 270 interactive pdb debugger after the traceback printout. %pdb toggles
271 271 this feature on and off.
272 272
273 273 The initial state of this feature is set in your configuration
274 274 file (the option is ``InteractiveShell.pdb``).
275 275
276 276 If you want to just activate the debugger AFTER an exception has fired,
277 277 without having to type '%pdb on' and rerunning your code, you can use
278 278 the %debug magic."""
279 279
280 280 par = parameter_s.strip().lower()
281 281
282 282 if par:
283 283 try:
284 284 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
285 285 except KeyError:
286 286 print ('Incorrect argument. Use on/1, off/0, '
287 287 'or nothing for a toggle.')
288 288 return
289 289 else:
290 290 # toggle
291 291 new_pdb = not self.shell.call_pdb
292 292
293 293 # set on the shell
294 294 self.shell.call_pdb = new_pdb
295 295 print 'Automatic pdb calling has been turned',on_off(new_pdb)
296 296
297 297 @skip_doctest
298 298 @magic_arguments.magic_arguments()
299 299 @magic_arguments.argument('--breakpoint', '-b', metavar='FILE:LINE',
300 300 help="""
301 301 Set break point at LINE in FILE.
302 302 """
303 303 )
304 304 @magic_arguments.argument('statement', nargs='*',
305 305 help="""
306 306 Code to run in debugger.
307 307 You can omit this in cell magic mode.
308 308 """
309 309 )
310 310 @line_cell_magic
311 311 def debug(self, line='', cell=None):
312 312 """Activate the interactive debugger.
313 313
314 314 This magic command support two ways of activating debugger.
315 315 One is to activate debugger before executing code. This way, you
316 316 can set a break point, to step through the code from the point.
317 317 You can use this mode by giving statements to execute and optionally
318 318 a breakpoint.
319 319
320 320 The other one is to activate debugger in post-mortem mode. You can
321 321 activate this mode simply running %debug without any argument.
322 322 If an exception has just occurred, this lets you inspect its stack
323 323 frames interactively. Note that this will always work only on the last
324 324 traceback that occurred, so you must call this quickly after an
325 325 exception that you wish to inspect has fired, because if another one
326 326 occurs, it clobbers the previous one.
327 327
328 328 If you want IPython to automatically do this on every exception, see
329 329 the %pdb magic for more details.
330 330 """
331 331 args = magic_arguments.parse_argstring(self.debug, line)
332 332
333 333 if not (args.breakpoint or args.statement or cell):
334 334 self._debug_post_mortem()
335 335 else:
336 336 code = "\n".join(args.statement)
337 337 if cell:
338 338 code += "\n" + cell
339 339 self._debug_exec(code, args.breakpoint)
340 340
341 341 def _debug_post_mortem(self):
342 342 self.shell.debugger(force=True)
343 343
344 344 def _debug_exec(self, code, breakpoint):
345 345 if breakpoint:
346 346 (filename, bp_line) = breakpoint.split(':', 1)
347 347 bp_line = int(bp_line)
348 348 else:
349 349 (filename, bp_line) = (None, None)
350 350 self._run_with_debugger(code, self.shell.user_ns, filename, bp_line)
351 351
352 352 @line_magic
353 353 def tb(self, s):
354 354 """Print the last traceback with the currently active exception mode.
355 355
356 356 See %xmode for changing exception reporting modes."""
357 357 self.shell.showtraceback()
358 358
359 359 @skip_doctest
360 360 @line_magic
361 361 def run(self, parameter_s='', runner=None,
362 362 file_finder=get_py_filename):
363 363 """Run the named file inside IPython as a program.
364 364
365 365 Usage:
366 366 %run [-n -i -e -G]
367 367 [( -t [-N<N>] | -d [-b<N>] | -p [profile options] )]
368 368 ( -m mod | file ) [args]
369 369
370 370 Parameters after the filename are passed as command-line arguments to
371 371 the program (put in sys.argv). Then, control returns to IPython's
372 372 prompt.
373 373
374 374 This is similar to running at a system prompt:\\
375 375 $ python file args\\
376 376 but with the advantage of giving you IPython's tracebacks, and of
377 377 loading all variables into your interactive namespace for further use
378 378 (unless -p is used, see below).
379 379
380 380 The file is executed in a namespace initially consisting only of
381 381 __name__=='__main__' and sys.argv constructed as indicated. It thus
382 382 sees its environment as if it were being run as a stand-alone program
383 383 (except for sharing global objects such as previously imported
384 384 modules). But after execution, the IPython interactive namespace gets
385 385 updated with all variables defined in the program (except for __name__
386 386 and sys.argv). This allows for very convenient loading of code for
387 387 interactive work, while giving each program a 'clean sheet' to run in.
388 388
389 389 Arguments are expanded using shell-like glob match. Patterns
390 390 '*', '?', '[seq]' and '[!seq]' can be used. Additionally,
391 391 tilde '~' will be expanded into user's home directory. Unlike
392 392 real shells, quotation does not suppress expansions. Use
393 393 *two* back slashes (e.g., '\\\\*') to suppress expansions.
394 394 To completely disable these expansions, you can use -G flag.
395 395
396 396 Options:
397 397
398 398 -n: __name__ is NOT set to '__main__', but to the running file's name
399 399 without extension (as python does under import). This allows running
400 400 scripts and reloading the definitions in them without calling code
401 401 protected by an ' if __name__ == "__main__" ' clause.
402 402
403 403 -i: run the file in IPython's namespace instead of an empty one. This
404 404 is useful if you are experimenting with code written in a text editor
405 405 which depends on variables defined interactively.
406 406
407 407 -e: ignore sys.exit() calls or SystemExit exceptions in the script
408 408 being run. This is particularly useful if IPython is being used to
409 409 run unittests, which always exit with a sys.exit() call. In such
410 410 cases you are interested in the output of the test results, not in
411 411 seeing a traceback of the unittest module.
412 412
413 413 -t: print timing information at the end of the run. IPython will give
414 414 you an estimated CPU time consumption for your script, which under
415 415 Unix uses the resource module to avoid the wraparound problems of
416 416 time.clock(). Under Unix, an estimate of time spent on system tasks
417 417 is also given (for Windows platforms this is reported as 0.0).
418 418
419 419 If -t is given, an additional -N<N> option can be given, where <N>
420 420 must be an integer indicating how many times you want the script to
421 421 run. The final timing report will include total and per run results.
422 422
423 423 For example (testing the script uniq_stable.py)::
424 424
425 425 In [1]: run -t uniq_stable
426 426
427 427 IPython CPU timings (estimated):\\
428 428 User : 0.19597 s.\\
429 429 System: 0.0 s.\\
430 430
431 431 In [2]: run -t -N5 uniq_stable
432 432
433 433 IPython CPU timings (estimated):\\
434 434 Total runs performed: 5\\
435 435 Times : Total Per run\\
436 436 User : 0.910862 s, 0.1821724 s.\\
437 437 System: 0.0 s, 0.0 s.
438 438
439 439 -d: run your program under the control of pdb, the Python debugger.
440 440 This allows you to execute your program step by step, watch variables,
441 441 etc. Internally, what IPython does is similar to calling:
442 442
443 443 pdb.run('execfile("YOURFILENAME")')
444 444
445 445 with a breakpoint set on line 1 of your file. You can change the line
446 446 number for this automatic breakpoint to be <N> by using the -bN option
447 447 (where N must be an integer). For example::
448 448
449 449 %run -d -b40 myscript
450 450
451 451 will set the first breakpoint at line 40 in myscript.py. Note that
452 452 the first breakpoint must be set on a line which actually does
453 453 something (not a comment or docstring) for it to stop execution.
454 454
455 455 Or you can specify a breakpoint in a different file::
456 456
457 457 %run -d -b myotherfile.py:20 myscript
458 458
459 459 When the pdb debugger starts, you will see a (Pdb) prompt. You must
460 460 first enter 'c' (without quotes) to start execution up to the first
461 461 breakpoint.
462 462
463 463 Entering 'help' gives information about the use of the debugger. You
464 464 can easily see pdb's full documentation with "import pdb;pdb.help()"
465 465 at a prompt.
466 466
467 467 -p: run program under the control of the Python profiler module (which
468 468 prints a detailed report of execution times, function calls, etc).
469 469
470 470 You can pass other options after -p which affect the behavior of the
471 471 profiler itself. See the docs for %prun for details.
472 472
473 473 In this mode, the program's variables do NOT propagate back to the
474 474 IPython interactive namespace (because they remain in the namespace
475 475 where the profiler executes them).
476 476
477 477 Internally this triggers a call to %prun, see its documentation for
478 478 details on the options available specifically for profiling.
479 479
480 480 There is one special usage for which the text above doesn't apply:
481 481 if the filename ends with .ipy, the file is run as ipython script,
482 482 just as if the commands were written on IPython prompt.
483 483
484 484 -m: specify module name to load instead of script path. Similar to
485 485 the -m option for the python interpreter. Use this option last if you
486 486 want to combine with other %run options. Unlike the python interpreter
487 487 only source modules are allowed no .pyc or .pyo files.
488 488 For example::
489 489
490 490 %run -m example
491 491
492 492 will run the example module.
493 493
494 494 -G: disable shell-like glob expansion of arguments.
495 495
496 496 """
497 497
498 498 # get arguments and set sys.argv for program to be run.
499 499 opts, arg_lst = self.parse_options(parameter_s,
500 500 'nidtN:b:pD:l:rs:T:em:G',
501 501 mode='list', list_all=1)
502 502 if "m" in opts:
503 503 modulename = opts["m"][0]
504 504 modpath = find_mod(modulename)
505 505 if modpath is None:
506 506 warn('%r is not a valid modulename on sys.path'%modulename)
507 507 return
508 508 arg_lst = [modpath] + arg_lst
509 509 try:
510 510 filename = file_finder(arg_lst[0])
511 511 except IndexError:
512 512 warn('you must provide at least a filename.')
513 513 print '\n%run:\n', oinspect.getdoc(self.run)
514 514 return
515 515 except IOError as e:
516 516 try:
517 517 msg = str(e)
518 518 except UnicodeError:
519 519 msg = e.message
520 520 error(msg)
521 521 return
522 522
523 523 if filename.lower().endswith('.ipy'):
524 524 with preserve_keys(self.shell.user_ns, '__file__'):
525 525 self.shell.user_ns['__file__'] = filename
526 526 self.shell.safe_execfile_ipy(filename)
527 527 return
528 528
529 529 # Control the response to exit() calls made by the script being run
530 530 exit_ignore = 'e' in opts
531 531
532 532 # Make sure that the running script gets a proper sys.argv as if it
533 533 # were run from a system shell.
534 534 save_argv = sys.argv # save it for later restoring
535 535
536 536 if 'G' in opts:
537 537 args = arg_lst[1:]
538 538 else:
539 539 # tilde and glob expansion
540 540 args = shellglob(map(os.path.expanduser, arg_lst[1:]))
541 541
542 542 sys.argv = [filename] + args # put in the proper filename
543 543 # protect sys.argv from potential unicode strings on Python 2:
544 544 if not py3compat.PY3:
545 545 sys.argv = [ py3compat.cast_bytes(a) for a in sys.argv ]
546 546
547 547 if 'i' in opts:
548 548 # Run in user's interactive namespace
549 549 prog_ns = self.shell.user_ns
550 550 __name__save = self.shell.user_ns['__name__']
551 551 prog_ns['__name__'] = '__main__'
552 552 main_mod = self.shell.user_module
553 553 else:
554 554 # Run in a fresh, empty namespace
555 555 if 'n' in opts:
556 556 name = os.path.splitext(os.path.basename(filename))[0]
557 557 else:
558 558 name = '__main__'
559 559
560 560 # The shell MUST hold a reference to prog_ns so after %run
561 561 # exits, the python deletion mechanism doesn't zero it out
562 562 # (leaving dangling references). See interactiveshell for details
563 563 main_mod = self.shell.new_main_mod(filename)
564 564 prog_ns = main_mod.__dict__
565 565 prog_ns['__name__'] = name
566 566
567 567 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
568 568 # set the __file__ global in the script's namespace
569 569 prog_ns['__file__'] = filename
570 570
571 571 # pickle fix. See interactiveshell for an explanation. But we need to
572 572 # make sure that, if we overwrite __main__, we replace it at the end
573 573 main_mod_name = prog_ns['__name__']
574 574
575 575 if main_mod_name == '__main__':
576 576 restore_main = sys.modules['__main__']
577 577 else:
578 578 restore_main = False
579 579
580 580 # This needs to be undone at the end to prevent holding references to
581 581 # every single object ever created.
582 582 sys.modules[main_mod_name] = main_mod
583 583
584 584 if 'p' in opts or 'd' in opts:
585 585 if 'm' in opts:
586 586 code = 'run_module(modulename, prog_ns)'
587 587 code_ns = {
588 588 'run_module': self.shell.safe_run_module,
589 589 'prog_ns': prog_ns,
590 590 'modulename': modulename,
591 591 }
592 592 else:
593 593 code = 'execfile(filename, prog_ns)'
594 594 code_ns = {
595 595 'execfile': self.shell.safe_execfile,
596 596 'prog_ns': prog_ns,
597 597 'filename': get_py_filename(filename),
598 598 }
599 599
600 600 try:
601 601 stats = None
602 602 with self.shell.readline_no_record:
603 603 if 'p' in opts:
604 604 stats = self._run_with_profiler(code, opts, code_ns)
605 605 else:
606 606 if 'd' in opts:
607 607 bp_file, bp_line = parse_breakpoint(
608 608 opts.get('b', ['1'])[0], filename)
609 609 self._run_with_debugger(
610 610 code, code_ns, filename, bp_line, bp_file)
611 611 else:
612 612 if 'm' in opts:
613 613 def run():
614 614 self.shell.safe_run_module(modulename, prog_ns)
615 615 else:
616 616 if runner is None:
617 617 runner = self.default_runner
618 618 if runner is None:
619 619 runner = self.shell.safe_execfile
620 620
621 621 def run():
622 622 runner(filename, prog_ns, prog_ns,
623 623 exit_ignore=exit_ignore)
624 624
625 625 if 't' in opts:
626 626 # timed execution
627 627 try:
628 628 nruns = int(opts['N'][0])
629 629 if nruns < 1:
630 630 error('Number of runs must be >=1')
631 631 return
632 632 except (KeyError):
633 633 nruns = 1
634 634 self._run_with_timing(run, nruns)
635 635 else:
636 636 # regular execution
637 637 run()
638 638
639 639 if 'i' in opts:
640 640 self.shell.user_ns['__name__'] = __name__save
641 641 else:
642 642 # update IPython interactive namespace
643 643
644 644 # Some forms of read errors on the file may mean the
645 645 # __name__ key was never set; using pop we don't have to
646 646 # worry about a possible KeyError.
647 647 prog_ns.pop('__name__', None)
648 648
649 649 with preserve_keys(self.shell.user_ns, '__file__'):
650 650 self.shell.user_ns.update(prog_ns)
651 651 finally:
652 652 # It's a bit of a mystery why, but __builtins__ can change from
653 653 # being a module to becoming a dict missing some key data after
654 654 # %run. As best I can see, this is NOT something IPython is doing
655 655 # at all, and similar problems have been reported before:
656 656 # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html
657 657 # Since this seems to be done by the interpreter itself, the best
658 658 # we can do is to at least restore __builtins__ for the user on
659 659 # exit.
660 660 self.shell.user_ns['__builtins__'] = builtin_mod
661 661
662 662 # Ensure key global structures are restored
663 663 sys.argv = save_argv
664 664 if restore_main:
665 665 sys.modules['__main__'] = restore_main
666 666 else:
667 667 # Remove from sys.modules the reference to main_mod we'd
668 668 # added. Otherwise it will trap references to objects
669 669 # contained therein.
670 670 del sys.modules[main_mod_name]
671 671
672 672 return stats
673 673
674 674 def _run_with_debugger(self, code, code_ns, filename=None,
675 675 bp_line=None, bp_file=None):
676 676 """
677 677 Run `code` in debugger with a break point.
678 678
679 679 Parameters
680 680 ----------
681 681 code : str
682 682 Code to execute.
683 683 code_ns : dict
684 684 A namespace in which `code` is executed.
685 685 filename : str
686 686 `code` is ran as if it is in `filename`.
687 687 bp_line : int, optional
688 688 Line number of the break point.
689 689 bp_file : str, optional
690 690 Path to the file in which break point is specified.
691 691 `filename` is used if not given.
692 692
693 693 Raises
694 694 ------
695 695 UsageError
696 696 If the break point given by `bp_line` is not valid.
697 697
698 698 """
699 699 deb = debugger.Pdb(self.shell.colors)
700 700 # reset Breakpoint state, which is moronically kept
701 701 # in a class
702 702 bdb.Breakpoint.next = 1
703 703 bdb.Breakpoint.bplist = {}
704 704 bdb.Breakpoint.bpbynumber = [None]
705 705 if bp_line is not None:
706 706 # Set an initial breakpoint to stop execution
707 707 maxtries = 10
708 708 bp_file = bp_file or filename
709 709 checkline = deb.checkline(bp_file, bp_line)
710 710 if not checkline:
711 711 for bp in range(bp_line + 1, bp_line + maxtries + 1):
712 712 if deb.checkline(bp_file, bp):
713 713 break
714 714 else:
715 715 msg = ("\nI failed to find a valid line to set "
716 716 "a breakpoint\n"
717 717 "after trying up to line: %s.\n"
718 718 "Please set a valid breakpoint manually "
719 719 "with the -b option." % bp)
720 720 raise UsageError(msg)
721 721 # if we find a good linenumber, set the breakpoint
722 722 deb.do_break('%s:%s' % (bp_file, bp_line))
723 723
724 724 if filename:
725 725 # Mimic Pdb._runscript(...)
726 726 deb._wait_for_mainpyfile = True
727 727 deb.mainpyfile = deb.canonic(filename)
728 728
729 729 # Start file run
730 730 print "NOTE: Enter 'c' at the %s prompt to continue execution." % deb.prompt
731 731 try:
732 732 if filename:
733 733 # save filename so it can be used by methods on the deb object
734 734 deb._exec_filename = filename
735 735 deb.run(code, code_ns)
736 736
737 737 except:
738 738 etype, value, tb = sys.exc_info()
739 739 # Skip three frames in the traceback: the %run one,
740 740 # one inside bdb.py, and the command-line typed by the
741 741 # user (run by exec in pdb itself).
742 742 self.shell.InteractiveTB(etype, value, tb, tb_offset=3)
743 743
744 744 @staticmethod
745 745 def _run_with_timing(run, nruns):
746 746 """
747 747 Run function `run` and print timing information.
748 748
749 749 Parameters
750 750 ----------
751 751 run : callable
752 752 Any callable object which takes no argument.
753 753 nruns : int
754 754 Number of times to execute `run`.
755 755
756 756 """
757 757 twall0 = time.time()
758 758 if nruns == 1:
759 759 t0 = clock2()
760 760 run()
761 761 t1 = clock2()
762 762 t_usr = t1[0] - t0[0]
763 763 t_sys = t1[1] - t0[1]
764 764 print "\nIPython CPU timings (estimated):"
765 765 print " User : %10.2f s." % t_usr
766 766 print " System : %10.2f s." % t_sys
767 767 else:
768 768 runs = range(nruns)
769 769 t0 = clock2()
770 770 for nr in runs:
771 771 run()
772 772 t1 = clock2()
773 773 t_usr = t1[0] - t0[0]
774 774 t_sys = t1[1] - t0[1]
775 775 print "\nIPython CPU timings (estimated):"
776 776 print "Total runs performed:", nruns
777 777 print " Times : %10s %10s" % ('Total', 'Per run')
778 778 print " User : %10.2f s, %10.2f s." % (t_usr, t_usr / nruns)
779 779 print " System : %10.2f s, %10.2f s." % (t_sys, t_sys / nruns)
780 780 twall1 = time.time()
781 781 print "Wall time: %10.2f s." % (twall1 - twall0)
782 782
783 783 @skip_doctest
784 784 @line_cell_magic
785 785 def timeit(self, line='', cell=None):
786 786 """Time execution of a Python statement or expression
787 787
788 788 Usage, in line mode:
789 789 %timeit [-n<N> -r<R> [-t|-c]] statement
790 790 or in cell mode:
791 791 %%timeit [-n<N> -r<R> [-t|-c]] setup_code
792 792 code
793 793 code...
794 794
795 795 Time execution of a Python statement or expression using the timeit
796 796 module. This function can be used both as a line and cell magic:
797 797
798 798 - In line mode you can time a single-line statement (though multiple
799 799 ones can be chained with using semicolons).
800 800
801 801 - In cell mode, the statement in the first line is used as setup code
802 802 (executed but not timed) and the body of the cell is timed. The cell
803 803 body has access to any variables created in the setup code.
804 804
805 805 Options:
806 806 -n<N>: execute the given statement <N> times in a loop. If this value
807 807 is not given, a fitting value is chosen.
808 808
809 809 -r<R>: repeat the loop iteration <R> times and take the best result.
810 810 Default: 3
811 811
812 812 -t: use time.time to measure the time, which is the default on Unix.
813 813 This function measures wall time.
814 814
815 815 -c: use time.clock to measure the time, which is the default on
816 816 Windows and measures wall time. On Unix, resource.getrusage is used
817 817 instead and returns the CPU user time.
818 818
819 819 -p<P>: use a precision of <P> digits to display the timing result.
820 820 Default: 3
821 821
822 822
823 823 Examples
824 824 --------
825 825 ::
826 826
827 827 In [1]: %timeit pass
828 828 10000000 loops, best of 3: 53.3 ns per loop
829 829
830 830 In [2]: u = None
831 831
832 832 In [3]: %timeit u is None
833 833 10000000 loops, best of 3: 184 ns per loop
834 834
835 835 In [4]: %timeit -r 4 u == None
836 836 1000000 loops, best of 4: 242 ns per loop
837 837
838 838 In [5]: import time
839 839
840 840 In [6]: %timeit -n1 time.sleep(2)
841 841 1 loops, best of 3: 2 s per loop
842 842
843 843
844 844 The times reported by %timeit will be slightly higher than those
845 845 reported by the timeit.py script when variables are accessed. This is
846 846 due to the fact that %timeit executes the statement in the namespace
847 847 of the shell, compared with timeit.py, which uses a single setup
848 848 statement to import function or create variables. Generally, the bias
849 849 does not matter as long as results from timeit.py are not mixed with
850 850 those from %timeit."""
851 851
852 852 import timeit
853 853
854 854 opts, stmt = self.parse_options(line,'n:r:tcp:',
855 855 posix=False, strict=False)
856 856 if stmt == "" and cell is None:
857 857 return
858 858
859 859 timefunc = timeit.default_timer
860 860 number = int(getattr(opts, "n", 0))
861 861 repeat = int(getattr(opts, "r", timeit.default_repeat))
862 862 precision = int(getattr(opts, "p", 3))
863 863 if hasattr(opts, "t"):
864 864 timefunc = time.time
865 865 if hasattr(opts, "c"):
866 866 timefunc = clock
867 867
868 868 timer = timeit.Timer(timer=timefunc)
869 869 # this code has tight coupling to the inner workings of timeit.Timer,
870 870 # but is there a better way to achieve that the code stmt has access
871 871 # to the shell namespace?
872 872 transform = self.shell.input_splitter.transform_cell
873 873
874 874 if cell is None:
875 875 # called as line magic
876 876 ast_setup = ast.parse("pass")
877 877 ast_stmt = ast.parse(transform(stmt))
878 878 else:
879 879 ast_setup = ast.parse(transform(stmt))
880 880 ast_stmt = ast.parse(transform(cell))
881 881
882 882 ast_setup = self.shell.transform_ast(ast_setup)
883 883 ast_stmt = self.shell.transform_ast(ast_stmt)
884 884
885 885 # This codestring is taken from timeit.template - we fill it in as an
886 886 # AST, so that we can apply our AST transformations to the user code
887 887 # without affecting the timing code.
888 888 timeit_ast_template = ast.parse('def inner(_it, _timer):\n'
889 889 ' setup\n'
890 890 ' _t0 = _timer()\n'
891 891 ' for _i in _it:\n'
892 892 ' stmt\n'
893 893 ' _t1 = _timer()\n'
894 894 ' return _t1 - _t0\n')
895 895
896 896 class TimeitTemplateFiller(ast.NodeTransformer):
897 897 "This is quite tightly tied to the template definition above."
898 898 def visit_FunctionDef(self, node):
899 899 "Fill in the setup statement"
900 900 self.generic_visit(node)
901 901 if node.name == "inner":
902 902 node.body[:1] = ast_setup.body
903 903
904 904 return node
905 905
906 906 def visit_For(self, node):
907 907 "Fill in the statement to be timed"
908 908 if getattr(getattr(node.body[0], 'value', None), 'id', None) == 'stmt':
909 909 node.body = ast_stmt.body
910 910 return node
911 911
912 912 timeit_ast = TimeitTemplateFiller().visit(timeit_ast_template)
913 913 timeit_ast = ast.fix_missing_locations(timeit_ast)
914 914
915 915 # Track compilation time so it can be reported if too long
916 916 # Minimum time above which compilation time will be reported
917 917 tc_min = 0.1
918 918
919 919 t0 = clock()
920 920 code = compile(timeit_ast, "<magic-timeit>", "exec")
921 921 tc = clock()-t0
922 922
923 923 ns = {}
924 924 exec code in self.shell.user_ns, ns
925 925 timer.inner = ns["inner"]
926 926
927 927 if number == 0:
928 928 # determine number so that 0.2 <= total time < 2.0
929 929 number = 1
930 930 for i in range(1, 10):
931 931 if timer.timeit(number) >= 0.2:
932 932 break
933 933 number *= 10
934 934
935 935 best = min(timer.repeat(repeat, number)) / number
936 936
937 937 print u"%d loops, best of %d: %s per loop" % (number, repeat,
938 938 _format_time(best, precision))
939 939 if tc > tc_min:
940 940 print "Compiler time: %.2f s" % tc
941 941
942 942 @skip_doctest
943 943 @needs_local_scope
944 944 @line_cell_magic
945 945 def time(self,line='', cell=None, local_ns=None):
946 946 """Time execution of a Python statement or expression.
947 947
948 948 The CPU and wall clock times are printed, and the value of the
949 949 expression (if any) is returned. Note that under Win32, system time
950 950 is always reported as 0, since it can not be measured.
951 951
952 952 This function can be used both as a line and cell magic:
953 953
954 954 - In line mode you can time a single-line statement (though multiple
955 955 ones can be chained with using semicolons).
956 956
957 957 - In cell mode, you can time the cell body (a directly
958 958 following statement raises an error).
959 959
960 960 This function provides very basic timing functionality. Use the timeit
961 961 magic for more controll over the measurement.
962 962
963 963 Examples
964 964 --------
965 965 ::
966 966
967 967 In [1]: %time 2**128
968 968 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
969 969 Wall time: 0.00
970 970 Out[1]: 340282366920938463463374607431768211456L
971 971
972 972 In [2]: n = 1000000
973 973
974 974 In [3]: %time sum(range(n))
975 975 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
976 976 Wall time: 1.37
977 977 Out[3]: 499999500000L
978 978
979 979 In [4]: %time print 'hello world'
980 980 hello world
981 981 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
982 982 Wall time: 0.00
983 983
984 984 Note that the time needed by Python to compile the given expression
985 985 will be reported if it is more than 0.1s. In this example, the
986 986 actual exponentiation is done by Python at compilation time, so while
987 987 the expression can take a noticeable amount of time to compute, that
988 988 time is purely due to the compilation:
989 989
990 990 In [5]: %time 3**9999;
991 991 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
992 992 Wall time: 0.00 s
993 993
994 994 In [6]: %time 3**999999;
995 995 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
996 996 Wall time: 0.00 s
997 997 Compiler : 0.78 s
998 998 """
999 999
1000 1000 # fail immediately if the given expression can't be compiled
1001 1001
1002 1002 if line and cell:
1003 1003 raise UsageError("Can't use statement directly after '%%time'!")
1004 1004
1005 1005 if cell:
1006 1006 expr = self.shell.input_transformer_manager.transform_cell(cell)
1007 1007 else:
1008 1008 expr = self.shell.input_transformer_manager.transform_cell(line)
1009 1009
1010 1010 # Minimum time above which parse time will be reported
1011 1011 tp_min = 0.1
1012 1012
1013 1013 t0 = clock()
1014 1014 expr_ast = ast.parse(expr)
1015 1015 tp = clock()-t0
1016 1016
1017 1017 # Apply AST transformations
1018 1018 expr_ast = self.shell.transform_ast(expr_ast)
1019 1019
1020 1020 # Minimum time above which compilation time will be reported
1021 1021 tc_min = 0.1
1022 1022
1023 1023 if len(expr_ast.body)==1 and isinstance(expr_ast.body[0], ast.Expr):
1024 1024 mode = 'eval'
1025 1025 source = '<timed eval>'
1026 1026 expr_ast = ast.Expression(expr_ast.body[0].value)
1027 1027 else:
1028 1028 mode = 'exec'
1029 1029 source = '<timed exec>'
1030 1030 t0 = clock()
1031 1031 code = compile(expr_ast, source, mode)
1032 1032 tc = clock()-t0
1033 1033
1034 1034 # skew measurement as little as possible
1035 1035 glob = self.shell.user_ns
1036 1036 wtime = time.time
1037 1037 # time execution
1038 1038 wall_st = wtime()
1039 1039 if mode=='eval':
1040 1040 st = clock2()
1041 1041 out = eval(code, glob, local_ns)
1042 1042 end = clock2()
1043 1043 else:
1044 1044 st = clock2()
1045 1045 exec code in glob, local_ns
1046 1046 end = clock2()
1047 1047 out = None
1048 1048 wall_end = wtime()
1049 1049 # Compute actual times and report
1050 1050 wall_time = wall_end-wall_st
1051 1051 cpu_user = end[0]-st[0]
1052 1052 cpu_sys = end[1]-st[1]
1053 1053 cpu_tot = cpu_user+cpu_sys
1054 1054 # On windows cpu_sys is always zero, so no new information to the next print
1055 1055 if sys.platform != 'win32':
1056 1056 print "CPU times: user %s, sys: %s, total: %s" % \
1057 1057 (_format_time(cpu_user),_format_time(cpu_sys),_format_time(cpu_tot))
1058 1058 print "Wall time: %s" % _format_time(wall_time)
1059 1059 if tc > tc_min:
1060 1060 print "Compiler : %s" % _format_time(tc)
1061 1061 if tp > tp_min:
1062 1062 print "Parser : %s" % _format_time(tp)
1063 1063 return out
1064 1064
1065 1065 @skip_doctest
1066 1066 @line_magic
1067 1067 def macro(self, parameter_s=''):
1068 1068 """Define a macro for future re-execution. It accepts ranges of history,
1069 1069 filenames or string objects.
1070 1070
1071 1071 Usage:\\
1072 1072 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
1073 1073
1074 1074 Options:
1075 1075
1076 1076 -r: use 'raw' input. By default, the 'processed' history is used,
1077 1077 so that magics are loaded in their transformed version to valid
1078 1078 Python. If this option is given, the raw input as typed at the
1079 1079 command line is used instead.
1080 1080
1081 1081 -q: quiet macro definition. By default, a tag line is printed
1082 1082 to indicate the macro has been created, and then the contents of
1083 1083 the macro are printed. If this option is given, then no printout
1084 1084 is produced once the macro is created.
1085 1085
1086 1086 This will define a global variable called `name` which is a string
1087 1087 made of joining the slices and lines you specify (n1,n2,... numbers
1088 1088 above) from your input history into a single string. This variable
1089 1089 acts like an automatic function which re-executes those lines as if
1090 1090 you had typed them. You just type 'name' at the prompt and the code
1091 1091 executes.
1092 1092
1093 1093 The syntax for indicating input ranges is described in %history.
1094 1094
1095 1095 Note: as a 'hidden' feature, you can also use traditional python slice
1096 1096 notation, where N:M means numbers N through M-1.
1097 1097
1098 1098 For example, if your history contains (print using %hist -n )::
1099 1099
1100 1100 44: x=1
1101 1101 45: y=3
1102 1102 46: z=x+y
1103 1103 47: print x
1104 1104 48: a=5
1105 1105 49: print 'x',x,'y',y
1106 1106
1107 1107 you can create a macro with lines 44 through 47 (included) and line 49
1108 1108 called my_macro with::
1109 1109
1110 1110 In [55]: %macro my_macro 44-47 49
1111 1111
1112 1112 Now, typing `my_macro` (without quotes) will re-execute all this code
1113 1113 in one pass.
1114 1114
1115 1115 You don't need to give the line-numbers in order, and any given line
1116 1116 number can appear multiple times. You can assemble macros with any
1117 1117 lines from your input history in any order.
1118 1118
1119 1119 The macro is a simple object which holds its value in an attribute,
1120 1120 but IPython's display system checks for macros and executes them as
1121 1121 code instead of printing them when you type their name.
1122 1122
1123 1123 You can view a macro's contents by explicitly printing it with::
1124 1124
1125 1125 print macro_name
1126 1126
1127 1127 """
1128 1128 opts,args = self.parse_options(parameter_s,'rq',mode='list')
1129 1129 if not args: # List existing macros
1130 1130 return sorted(k for k,v in self.shell.user_ns.iteritems() if\
1131 1131 isinstance(v, Macro))
1132 1132 if len(args) == 1:
1133 1133 raise UsageError(
1134 1134 "%macro insufficient args; usage '%macro name n1-n2 n3-4...")
1135 1135 name, codefrom = args[0], " ".join(args[1:])
1136 1136
1137 1137 #print 'rng',ranges # dbg
1138 1138 try:
1139 1139 lines = self.shell.find_user_code(codefrom, 'r' in opts)
1140 1140 except (ValueError, TypeError) as e:
1141 1141 print e.args[0]
1142 1142 return
1143 1143 macro = Macro(lines)
1144 1144 self.shell.define_macro(name, macro)
1145 1145 if not ( 'q' in opts) :
1146 1146 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
1147 1147 print '=== Macro contents: ==='
1148 1148 print macro,
1149 1149
1150 1150 @magic_arguments.magic_arguments()
1151 1151 @magic_arguments.argument('output', type=str, default='', nargs='?',
1152 1152 help="""The name of the variable in which to store output.
1153 1153 This is a utils.io.CapturedIO object with stdout/err attributes
1154 1154 for the text of the captured output.
1155 1155
1156 1156 CapturedOutput also has a show() method for displaying the output,
1157 1157 and __call__ as well, so you can use that to quickly display the
1158 1158 output.
1159 1159
1160 1160 If unspecified, captured output is discarded.
1161 1161 """
1162 1162 )
1163 1163 @magic_arguments.argument('--no-stderr', action="store_true",
1164 1164 help="""Don't capture stderr."""
1165 1165 )
1166 1166 @magic_arguments.argument('--no-stdout', action="store_true",
1167 1167 help="""Don't capture stdout."""
1168 1168 )
1169 @magic_arguments.argument('--no-display', action="store_true",
1170 help="""Don't capture IPython's rich display."""
1171 )
1169 1172 @cell_magic
1170 1173 def capture(self, line, cell):
1171 """run the cell, capturing stdout/err"""
1174 """run the cell, capturing stdout, stderr, and IPython's rich display() calls."""
1172 1175 args = magic_arguments.parse_argstring(self.capture, line)
1173 1176 out = not args.no_stdout
1174 1177 err = not args.no_stderr
1175 with capture_output(out, err) as io:
1178 disp = not args.no_display
1179 with capture_output(out, err, disp) as io:
1176 1180 self.shell.run_cell(cell)
1177 1181 if args.output:
1178 1182 self.shell.user_ns[args.output] = io
1179 1183
1180 1184 def parse_breakpoint(text, current_file):
1181 1185 '''Returns (file, line) for file:line and (current_file, line) for line'''
1182 1186 colon = text.find(':')
1183 1187 if colon == -1:
1184 1188 return current_file, int(text)
1185 1189 else:
1186 1190 return text[:colon], int(text[colon+1:])
1187 1191
1188 1192 def _format_time(timespan, precision=3):
1189 1193 """Formats the timespan in a human readable form"""
1190 1194 import math
1191 1195
1192 1196 if timespan >= 60.0:
1193 1197 # we have more than a minute, format that in a human readable form
1194 1198 # Idea from http://snipplr.com/view/5713/
1195 1199 parts = [("d", 60*60*24),("h", 60*60),("min", 60), ("s", 1)]
1196 1200 time = []
1197 1201 leftover = timespan
1198 1202 for suffix, length in parts:
1199 1203 value = int(leftover / length)
1200 1204 if value > 0:
1201 1205 leftover = leftover % length
1202 1206 time.append(u'%s%s' % (str(value), suffix))
1203 1207 if leftover < 1:
1204 1208 break
1205 1209 return " ".join(time)
1206 1210
1207 1211
1208 1212 # Unfortunately the unicode 'micro' symbol can cause problems in
1209 1213 # certain terminals.
1210 1214 # See bug: https://bugs.launchpad.net/ipython/+bug/348466
1211 1215 # Try to prevent crashes by being more secure than it needs to
1212 1216 # E.g. eclipse is able to print a µ, but has no sys.stdout.encoding set.
1213 1217 units = [u"s", u"ms",u'us',"ns"] # the save value
1214 1218 if hasattr(sys.stdout, 'encoding') and sys.stdout.encoding:
1215 1219 try:
1216 1220 u'\xb5'.encode(sys.stdout.encoding)
1217 1221 units = [u"s", u"ms",u'\xb5s',"ns"]
1218 1222 except:
1219 1223 pass
1220 1224 scaling = [1, 1e3, 1e6, 1e9]
1221 1225
1222 1226 if timespan > 0.0:
1223 1227 order = min(-int(math.floor(math.log10(timespan)) // 3), 3)
1224 1228 else:
1225 1229 order = 3
1226 1230 ret = u"%.*g %s" % (precision, timespan * scaling[order], units[order])
1227 1231 return ret
@@ -1,152 +1,162 b''
1 1 # encoding: utf-8
2 2 """
3 3 IO capturing utilities.
4 4 """
5 5
6 6 #-----------------------------------------------------------------------------
7 7 # Copyright (C) 2013 The IPython Development Team
8 8 #
9 9 # Distributed under the terms of the BSD License. The full license is in
10 10 # the file COPYING, distributed as part of this software.
11 11 #-----------------------------------------------------------------------------
12 12 from __future__ import print_function
13 13
14 14 #-----------------------------------------------------------------------------
15 15 # Imports
16 16 #-----------------------------------------------------------------------------
17 17
18 18 import sys
19 19 from StringIO import StringIO
20 20
21 21 #-----------------------------------------------------------------------------
22 22 # Classes and functions
23 23 #-----------------------------------------------------------------------------
24 24
25 25
26 26 class RichOutput(object):
27 27 def __init__(self, source, data, metadata):
28 28 self.source = source
29 29 self.data = data or {}
30 30 self.metadata = metadata or {}
31 31
32 32 def display(self):
33 33 from IPython.display import publish_display_data
34 34 publish_display_data(self.source, self.data, self.metadata)
35 35
36 36 def _repr_mime_(self, mime):
37 37 if mime not in self.data:
38 38 return
39 39 data = self.data[mime]
40 40 if mime in self.metadata:
41 41 return data, self.metadata[mime]
42 42 else:
43 43 return data
44 44
45 45 def _repr_html_(self):
46 46 return self._repr_mime_("text/html")
47 47
48 48 def _repr_latex_(self):
49 49 return self._repr_mime_("text/latex")
50 50
51 51 def _repr_json_(self):
52 52 return self._repr_mime_("application/json")
53 53
54 54 def _repr_javascript_(self):
55 55 return self._repr_mime_("application/javascript")
56 56
57 57 def _repr_png_(self):
58 58 return self._repr_mime_("image/png")
59 59
60 60 def _repr_jpeg_(self):
61 61 return self._repr_mime_("image/jpg")
62 62
63 63 def _repr_svg_(self):
64 64 return self._repr_mime_("image/svg+xml")
65 65
66 66
67 67 class CapturedIO(object):
68 """Simple object for containing captured stdout/err StringIO objects"""
68 """Simple object for containing captured stdout/err and rich display StringIO objects
69
70 Each instance `c` has three attributes:
71
72 c.stdout : standard output as a string
73 c.stderr : standard error as a string
74 c.outputs: a list of rich display outputs
75
76 Additionally, there's a `c.show()` method which will print all of the
77 above in the same order, and can be invoked simply via `c()`.
78 """
69 79
70 80 def __init__(self, stdout, stderr, outputs=None):
71 81 self._stdout = stdout
72 82 self._stderr = stderr
73 83 if outputs is None:
74 84 outputs = []
75 85 self._outputs = outputs
76 86
77 87 def __str__(self):
78 88 return self.stdout
79 89
80 90 @property
81 91 def stdout(self):
82 92 if not self._stdout:
83 93 return ''
84 94 return self._stdout.getvalue()
85 95
86 96 @property
87 97 def stderr(self):
88 98 if not self._stderr:
89 99 return ''
90 100 return self._stderr.getvalue()
91 101
92 102 @property
93 103 def outputs(self):
94 104 return [ RichOutput(s, d, md) for s, d, md in self._outputs ]
95 105
96 106 def show(self):
97 107 """write my output to sys.stdout/err as appropriate"""
98 108 sys.stdout.write(self.stdout)
99 109 sys.stderr.write(self.stderr)
100 110 sys.stdout.flush()
101 111 sys.stderr.flush()
102 112 for source, data, metadata in self._outputs:
103 113 RichOutput(source, data, metadata).display()
104 114
105 115 __call__ = show
106 116
107 117
108 118 class capture_output(object):
109 119 """context manager for capturing stdout/err"""
110 120 stdout = True
111 121 stderr = True
112 122 display = True
113 123
114 124 def __init__(self, stdout=True, stderr=True, display=True):
115 125 self.stdout = stdout
116 126 self.stderr = stderr
117 127 self.display = display
118 128 self.shell = None
119 129
120 130 def __enter__(self):
121 131 from IPython.core.getipython import get_ipython
122 132 from IPython.core.displaypub import CapturingDisplayPublisher
123 133
124 134 self.sys_stdout = sys.stdout
125 135 self.sys_stderr = sys.stderr
126 136
127 137 if self.display:
128 138 self.shell = get_ipython()
129 139 if self.shell is None:
130 140 self.save_display_pub = None
131 141 self.display = False
132 142
133 stdout = stderr = outputs = False
143 stdout = stderr = outputs = None
134 144 if self.stdout:
135 145 stdout = sys.stdout = StringIO()
136 146 if self.stderr:
137 147 stderr = sys.stderr = StringIO()
138 148 if self.display:
139 149 self.save_display_pub = self.shell.display_pub
140 150 self.shell.display_pub = CapturingDisplayPublisher()
141 151 outputs = self.shell.display_pub.outputs
142 152
143 153
144 154 return CapturedIO(stdout, stderr, outputs)
145 155
146 156 def __exit__(self, exc_type, exc_value, traceback):
147 157 sys.stdout = self.sys_stdout
148 158 sys.stderr = self.sys_stderr
149 159 if self.display and self.shell:
150 160 self.shell.display_pub = self.save_display_pub
151 161
152 162
@@ -1,12 +1,15 b''
1 1 =====================
2 2 Development version
3 3 =====================
4 4
5 5 This document describes in-flight development work.
6 6
7 - `%%capture` cell magic now captures the rich display output, not just
8 stdout/stderr
9
7 10
8 11 Backwards incompatible changes
9 12 ------------------------------
10 13
11 14 * Python 2.6 and 3.2 are no longer supported: the minimum required
12 15 Python versions are now 2.7 and 3.3.
General Comments 0
You need to be logged in to leave comments. Login now