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