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