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