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