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