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