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