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