##// END OF EJS Templates
%prun: Restore `stats.stream` after running `print_stream`....
Bradley M. Froehle -
Show More
@@ -1,1022 +1,1014 b''
1 1 """Implementation of execution-related magic functions.
2 2 """
3 3 #-----------------------------------------------------------------------------
4 4 # Copyright (c) 2012 The IPython Development Team.
5 5 #
6 6 # Distributed under the terms of the Modified BSD License.
7 7 #
8 8 # The full license is in the file COPYING.txt, distributed with this software.
9 9 #-----------------------------------------------------------------------------
10 10
11 11 #-----------------------------------------------------------------------------
12 12 # Imports
13 13 #-----------------------------------------------------------------------------
14 14
15 15 # Stdlib
16 16 import __builtin__ as builtin_mod
17 17 import bdb
18 18 import os
19 19 import sys
20 20 import time
21 21 from StringIO import StringIO
22 22
23 23 # cProfile was added in Python2.5
24 24 try:
25 25 import cProfile as profile
26 26 import pstats
27 27 except ImportError:
28 28 # profile isn't bundled by default in Debian for license reasons
29 29 try:
30 30 import profile, pstats
31 31 except ImportError:
32 32 profile = pstats = None
33 33
34 34 # Our own packages
35 35 from IPython.core import debugger, oinspect
36 36 from IPython.core import magic_arguments
37 37 from IPython.core import page
38 38 from IPython.core.error import UsageError
39 39 from IPython.core.macro import Macro
40 40 from IPython.core.magic import (Magics, magics_class, line_magic, cell_magic,
41 41 line_cell_magic, on_off, needs_local_scope)
42 42 from IPython.testing.skipdoctest import skip_doctest
43 43 from IPython.utils import py3compat
44 44 from IPython.utils.io import capture_output
45 45 from IPython.utils.ipstruct import Struct
46 46 from IPython.utils.module_paths import find_mod
47 47 from IPython.utils.path import get_py_filename, unquote_filename
48 48 from IPython.utils.timing import clock, clock2
49 49 from IPython.utils.warn import warn, error
50 50
51 51 #-----------------------------------------------------------------------------
52 52 # Magic implementation classes
53 53 #-----------------------------------------------------------------------------
54 54
55 55 @magics_class
56 56 class ExecutionMagics(Magics):
57 57 """Magics related to code execution, debugging, profiling, etc.
58 58
59 59 """
60 60
61 61 def __init__(self, shell):
62 62 super(ExecutionMagics, self).__init__(shell)
63 63 if profile is None:
64 64 self.prun = self.profile_missing_notice
65 65 # Default execution function used to actually run user code.
66 66 self.default_runner = None
67 67
68 68 def profile_missing_notice(self, *args, **kwargs):
69 69 error("""\
70 70 The profile module could not be found. It has been removed from the standard
71 71 python packages because of its non-free license. To use profiling, install the
72 72 python-profiler package from non-free.""")
73 73
74 74 @skip_doctest
75 75 @line_cell_magic
76 76 def prun(self, parameter_s='', cell=None, user_mode=True,
77 77 opts=None,arg_lst=None,prog_ns=None):
78 78
79 79 """Run a statement through the python code profiler.
80 80
81 81 Usage, in line mode:
82 82 %prun [options] statement
83 83
84 84 Usage, in cell mode:
85 85 %%prun [options] [statement]
86 86 code...
87 87 code...
88 88
89 89 In cell mode, the additional code lines are appended to the (possibly
90 90 empty) statement in the first line. Cell mode allows you to easily
91 91 profile multiline blocks without having to put them in a separate
92 92 function.
93 93
94 94 The given statement (which doesn't require quote marks) is run via the
95 95 python profiler in a manner similar to the profile.run() function.
96 96 Namespaces are internally managed to work correctly; profile.run
97 97 cannot be used in IPython because it makes certain assumptions about
98 98 namespaces which do not hold under IPython.
99 99
100 100 Options:
101 101
102 102 -l <limit>: you can place restrictions on what or how much of the
103 103 profile gets printed. The limit value can be:
104 104
105 105 * A string: only information for function names containing this string
106 106 is printed.
107 107
108 108 * An integer: only these many lines are printed.
109 109
110 110 * A float (between 0 and 1): this fraction of the report is printed
111 111 (for example, use a limit of 0.4 to see the topmost 40% only).
112 112
113 113 You can combine several limits with repeated use of the option. For
114 114 example, '-l __init__ -l 5' will print only the topmost 5 lines of
115 115 information about class constructors.
116 116
117 117 -r: return the pstats.Stats object generated by the profiling. This
118 118 object has all the information about the profile in it, and you can
119 119 later use it for further analysis or in other functions.
120 120
121 121 -s <key>: sort profile by given key. You can provide more than one key
122 122 by using the option several times: '-s key1 -s key2 -s key3...'. The
123 123 default sorting key is 'time'.
124 124
125 125 The following is copied verbatim from the profile documentation
126 126 referenced below:
127 127
128 128 When more than one key is provided, additional keys are used as
129 129 secondary criteria when the there is equality in all keys selected
130 130 before them.
131 131
132 132 Abbreviations can be used for any key names, as long as the
133 133 abbreviation is unambiguous. The following are the keys currently
134 134 defined:
135 135
136 136 Valid Arg Meaning
137 137 "calls" call count
138 138 "cumulative" cumulative time
139 139 "file" file name
140 140 "module" file name
141 141 "pcalls" primitive call count
142 142 "line" line number
143 143 "name" function name
144 144 "nfl" name/file/line
145 145 "stdname" standard name
146 146 "time" internal time
147 147
148 148 Note that all sorts on statistics are in descending order (placing
149 149 most time consuming items first), where as name, file, and line number
150 150 searches are in ascending order (i.e., alphabetical). The subtle
151 151 distinction between "nfl" and "stdname" is that the standard name is a
152 152 sort of the name as printed, which means that the embedded line
153 153 numbers get compared in an odd way. For example, lines 3, 20, and 40
154 154 would (if the file names were the same) appear in the string order
155 155 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
156 156 line numbers. In fact, sort_stats("nfl") is the same as
157 157 sort_stats("name", "file", "line").
158 158
159 159 -T <filename>: save profile results as shown on screen to a text
160 160 file. The profile is still shown on screen.
161 161
162 162 -D <filename>: save (via dump_stats) profile statistics to given
163 163 filename. This data is in a format understood by the pstats module, and
164 164 is generated by a call to the dump_stats() method of profile
165 165 objects. The profile is still shown on screen.
166 166
167 167 -q: suppress output to the pager. Best used with -T and/or -D above.
168 168
169 169 If you want to run complete programs under the profiler's control, use
170 170 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
171 171 contains profiler specific options as described here.
172 172
173 173 You can read the complete documentation for the profile module with::
174 174
175 175 In [1]: import profile; profile.help()
176 176 """
177 177
178 178 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
179 179
180 180 if user_mode: # regular user call
181 181 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:q',
182 182 list_all=True, posix=False)
183 183 namespace = self.shell.user_ns
184 184 if cell is not None:
185 185 arg_str += '\n' + cell
186 186 else: # called to run a program by %run -p
187 187 try:
188 188 filename = get_py_filename(arg_lst[0])
189 189 except IOError as e:
190 190 try:
191 191 msg = str(e)
192 192 except UnicodeError:
193 193 msg = e.message
194 194 error(msg)
195 195 return
196 196
197 197 arg_str = 'execfile(filename,prog_ns)'
198 198 namespace = {
199 199 'execfile': self.shell.safe_execfile,
200 200 'prog_ns': prog_ns,
201 201 'filename': filename
202 202 }
203 203
204 204 opts.merge(opts_def)
205 205
206 206 prof = profile.Profile()
207 207 try:
208 208 prof = prof.runctx(arg_str,namespace,namespace)
209 209 sys_exit = ''
210 210 except SystemExit:
211 211 sys_exit = """*** SystemExit exception caught in code being profiled."""
212 212
213 213 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
214 214
215 215 lims = opts.l
216 216 if lims:
217 217 lims = [] # rebuild lims with ints/floats/strings
218 218 for lim in opts.l:
219 219 try:
220 220 lims.append(int(lim))
221 221 except ValueError:
222 222 try:
223 223 lims.append(float(lim))
224 224 except ValueError:
225 225 lims.append(lim)
226 226
227 227 # Trap output.
228 228 stdout_trap = StringIO()
229
230 if hasattr(stats,'stream'):
231 # In newer versions of python, the stats object has a 'stream'
232 # attribute to write into.
229 stats_stream = stats.stream
230 try:
233 231 stats.stream = stdout_trap
234 232 stats.print_stats(*lims)
235 else:
236 # For older versions, we manually redirect stdout during printing
237 sys_stdout = sys.stdout
238 try:
239 sys.stdout = stdout_trap
240 stats.print_stats(*lims)
241 finally:
242 sys.stdout = sys_stdout
233 finally:
234 stats.stream = stats_stream
243 235
244 236 output = stdout_trap.getvalue()
245 237 output = output.rstrip()
246 238
247 239 if 'q' not in opts:
248 240 page.page(output)
249 241 print sys_exit,
250 242
251 243 dump_file = opts.D[0]
252 244 text_file = opts.T[0]
253 245 if dump_file:
254 246 dump_file = unquote_filename(dump_file)
255 247 prof.dump_stats(dump_file)
256 248 print '\n*** Profile stats marshalled to file',\
257 249 `dump_file`+'.',sys_exit
258 250 if text_file:
259 251 text_file = unquote_filename(text_file)
260 252 pfile = open(text_file,'w')
261 253 pfile.write(output)
262 254 pfile.close()
263 255 print '\n*** Profile printout saved to text file',\
264 256 `text_file`+'.',sys_exit
265 257
266 258 if opts.has_key('r'):
267 259 return stats
268 260 else:
269 261 return None
270 262
271 263 @line_magic
272 264 def pdb(self, parameter_s=''):
273 265 """Control the automatic calling of the pdb interactive debugger.
274 266
275 267 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
276 268 argument it works as a toggle.
277 269
278 270 When an exception is triggered, IPython can optionally call the
279 271 interactive pdb debugger after the traceback printout. %pdb toggles
280 272 this feature on and off.
281 273
282 274 The initial state of this feature is set in your configuration
283 275 file (the option is ``InteractiveShell.pdb``).
284 276
285 277 If you want to just activate the debugger AFTER an exception has fired,
286 278 without having to type '%pdb on' and rerunning your code, you can use
287 279 the %debug magic."""
288 280
289 281 par = parameter_s.strip().lower()
290 282
291 283 if par:
292 284 try:
293 285 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
294 286 except KeyError:
295 287 print ('Incorrect argument. Use on/1, off/0, '
296 288 'or nothing for a toggle.')
297 289 return
298 290 else:
299 291 # toggle
300 292 new_pdb = not self.shell.call_pdb
301 293
302 294 # set on the shell
303 295 self.shell.call_pdb = new_pdb
304 296 print 'Automatic pdb calling has been turned',on_off(new_pdb)
305 297
306 298 @line_magic
307 299 def debug(self, parameter_s=''):
308 300 """Activate the interactive debugger in post-mortem mode.
309 301
310 302 If an exception has just occurred, this lets you inspect its stack
311 303 frames interactively. Note that this will always work only on the last
312 304 traceback that occurred, so you must call this quickly after an
313 305 exception that you wish to inspect has fired, because if another one
314 306 occurs, it clobbers the previous one.
315 307
316 308 If you want IPython to automatically do this on every exception, see
317 309 the %pdb magic for more details.
318 310 """
319 311 self.shell.debugger(force=True)
320 312
321 313 @line_magic
322 314 def tb(self, s):
323 315 """Print the last traceback with the currently active exception mode.
324 316
325 317 See %xmode for changing exception reporting modes."""
326 318 self.shell.showtraceback()
327 319
328 320 @skip_doctest
329 321 @line_magic
330 322 def run(self, parameter_s='', runner=None,
331 323 file_finder=get_py_filename):
332 324 """Run the named file inside IPython as a program.
333 325
334 326 Usage:\\
335 327 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
336 328
337 329 Parameters after the filename are passed as command-line arguments to
338 330 the program (put in sys.argv). Then, control returns to IPython's
339 331 prompt.
340 332
341 333 This is similar to running at a system prompt:\\
342 334 $ python file args\\
343 335 but with the advantage of giving you IPython's tracebacks, and of
344 336 loading all variables into your interactive namespace for further use
345 337 (unless -p is used, see below).
346 338
347 339 The file is executed in a namespace initially consisting only of
348 340 __name__=='__main__' and sys.argv constructed as indicated. It thus
349 341 sees its environment as if it were being run as a stand-alone program
350 342 (except for sharing global objects such as previously imported
351 343 modules). But after execution, the IPython interactive namespace gets
352 344 updated with all variables defined in the program (except for __name__
353 345 and sys.argv). This allows for very convenient loading of code for
354 346 interactive work, while giving each program a 'clean sheet' to run in.
355 347
356 348 Options:
357 349
358 350 -n: __name__ is NOT set to '__main__', but to the running file's name
359 351 without extension (as python does under import). This allows running
360 352 scripts and reloading the definitions in them without calling code
361 353 protected by an ' if __name__ == "__main__" ' clause.
362 354
363 355 -i: run the file in IPython's namespace instead of an empty one. This
364 356 is useful if you are experimenting with code written in a text editor
365 357 which depends on variables defined interactively.
366 358
367 359 -e: ignore sys.exit() calls or SystemExit exceptions in the script
368 360 being run. This is particularly useful if IPython is being used to
369 361 run unittests, which always exit with a sys.exit() call. In such
370 362 cases you are interested in the output of the test results, not in
371 363 seeing a traceback of the unittest module.
372 364
373 365 -t: print timing information at the end of the run. IPython will give
374 366 you an estimated CPU time consumption for your script, which under
375 367 Unix uses the resource module to avoid the wraparound problems of
376 368 time.clock(). Under Unix, an estimate of time spent on system tasks
377 369 is also given (for Windows platforms this is reported as 0.0).
378 370
379 371 If -t is given, an additional -N<N> option can be given, where <N>
380 372 must be an integer indicating how many times you want the script to
381 373 run. The final timing report will include total and per run results.
382 374
383 375 For example (testing the script uniq_stable.py)::
384 376
385 377 In [1]: run -t uniq_stable
386 378
387 379 IPython CPU timings (estimated):\\
388 380 User : 0.19597 s.\\
389 381 System: 0.0 s.\\
390 382
391 383 In [2]: run -t -N5 uniq_stable
392 384
393 385 IPython CPU timings (estimated):\\
394 386 Total runs performed: 5\\
395 387 Times : Total Per run\\
396 388 User : 0.910862 s, 0.1821724 s.\\
397 389 System: 0.0 s, 0.0 s.
398 390
399 391 -d: run your program under the control of pdb, the Python debugger.
400 392 This allows you to execute your program step by step, watch variables,
401 393 etc. Internally, what IPython does is similar to calling:
402 394
403 395 pdb.run('execfile("YOURFILENAME")')
404 396
405 397 with a breakpoint set on line 1 of your file. You can change the line
406 398 number for this automatic breakpoint to be <N> by using the -bN option
407 399 (where N must be an integer). For example::
408 400
409 401 %run -d -b40 myscript
410 402
411 403 will set the first breakpoint at line 40 in myscript.py. Note that
412 404 the first breakpoint must be set on a line which actually does
413 405 something (not a comment or docstring) for it to stop execution.
414 406
415 407 When the pdb debugger starts, you will see a (Pdb) prompt. You must
416 408 first enter 'c' (without quotes) to start execution up to the first
417 409 breakpoint.
418 410
419 411 Entering 'help' gives information about the use of the debugger. You
420 412 can easily see pdb's full documentation with "import pdb;pdb.help()"
421 413 at a prompt.
422 414
423 415 -p: run program under the control of the Python profiler module (which
424 416 prints a detailed report of execution times, function calls, etc).
425 417
426 418 You can pass other options after -p which affect the behavior of the
427 419 profiler itself. See the docs for %prun for details.
428 420
429 421 In this mode, the program's variables do NOT propagate back to the
430 422 IPython interactive namespace (because they remain in the namespace
431 423 where the profiler executes them).
432 424
433 425 Internally this triggers a call to %prun, see its documentation for
434 426 details on the options available specifically for profiling.
435 427
436 428 There is one special usage for which the text above doesn't apply:
437 429 if the filename ends with .ipy, the file is run as ipython script,
438 430 just as if the commands were written on IPython prompt.
439 431
440 432 -m: specify module name to load instead of script path. Similar to
441 433 the -m option for the python interpreter. Use this option last if you
442 434 want to combine with other %run options. Unlike the python interpreter
443 435 only source modules are allowed no .pyc or .pyo files.
444 436 For example::
445 437
446 438 %run -m example
447 439
448 440 will run the example module.
449 441
450 442 """
451 443
452 444 # get arguments and set sys.argv for program to be run.
453 445 opts, arg_lst = self.parse_options(parameter_s, 'nidtN:b:pD:l:rs:T:em:',
454 446 mode='list', list_all=1)
455 447 if "m" in opts:
456 448 modulename = opts["m"][0]
457 449 modpath = find_mod(modulename)
458 450 if modpath is None:
459 451 warn('%r is not a valid modulename on sys.path'%modulename)
460 452 return
461 453 arg_lst = [modpath] + arg_lst
462 454 try:
463 455 filename = file_finder(arg_lst[0])
464 456 except IndexError:
465 457 warn('you must provide at least a filename.')
466 458 print '\n%run:\n', oinspect.getdoc(self.run)
467 459 return
468 460 except IOError as e:
469 461 try:
470 462 msg = str(e)
471 463 except UnicodeError:
472 464 msg = e.message
473 465 error(msg)
474 466 return
475 467
476 468 if filename.lower().endswith('.ipy'):
477 469 self.shell.safe_execfile_ipy(filename)
478 470 return
479 471
480 472 # Control the response to exit() calls made by the script being run
481 473 exit_ignore = 'e' in opts
482 474
483 475 # Make sure that the running script gets a proper sys.argv as if it
484 476 # were run from a system shell.
485 477 save_argv = sys.argv # save it for later restoring
486 478
487 479 # simulate shell expansion on arguments, at least tilde expansion
488 480 args = [ os.path.expanduser(a) for a in arg_lst[1:] ]
489 481
490 482 sys.argv = [filename] + args # put in the proper filename
491 483 # protect sys.argv from potential unicode strings on Python 2:
492 484 if not py3compat.PY3:
493 485 sys.argv = [ py3compat.cast_bytes(a) for a in sys.argv ]
494 486
495 487 if 'i' in opts:
496 488 # Run in user's interactive namespace
497 489 prog_ns = self.shell.user_ns
498 490 __name__save = self.shell.user_ns['__name__']
499 491 prog_ns['__name__'] = '__main__'
500 492 main_mod = self.shell.new_main_mod(prog_ns)
501 493 else:
502 494 # Run in a fresh, empty namespace
503 495 if 'n' in opts:
504 496 name = os.path.splitext(os.path.basename(filename))[0]
505 497 else:
506 498 name = '__main__'
507 499
508 500 main_mod = self.shell.new_main_mod()
509 501 prog_ns = main_mod.__dict__
510 502 prog_ns['__name__'] = name
511 503
512 504 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
513 505 # set the __file__ global in the script's namespace
514 506 prog_ns['__file__'] = filename
515 507
516 508 # pickle fix. See interactiveshell for an explanation. But we need to
517 509 # make sure that, if we overwrite __main__, we replace it at the end
518 510 main_mod_name = prog_ns['__name__']
519 511
520 512 if main_mod_name == '__main__':
521 513 restore_main = sys.modules['__main__']
522 514 else:
523 515 restore_main = False
524 516
525 517 # This needs to be undone at the end to prevent holding references to
526 518 # every single object ever created.
527 519 sys.modules[main_mod_name] = main_mod
528 520
529 521 try:
530 522 stats = None
531 523 with self.shell.readline_no_record:
532 524 if 'p' in opts:
533 525 stats = self.prun('', None, False, opts, arg_lst, prog_ns)
534 526 else:
535 527 if 'd' in opts:
536 528 deb = debugger.Pdb(self.shell.colors)
537 529 # reset Breakpoint state, which is moronically kept
538 530 # in a class
539 531 bdb.Breakpoint.next = 1
540 532 bdb.Breakpoint.bplist = {}
541 533 bdb.Breakpoint.bpbynumber = [None]
542 534 # Set an initial breakpoint to stop execution
543 535 maxtries = 10
544 536 bp = int(opts.get('b', [1])[0])
545 537 checkline = deb.checkline(filename, bp)
546 538 if not checkline:
547 539 for bp in range(bp + 1, bp + maxtries + 1):
548 540 if deb.checkline(filename, bp):
549 541 break
550 542 else:
551 543 msg = ("\nI failed to find a valid line to set "
552 544 "a breakpoint\n"
553 545 "after trying up to line: %s.\n"
554 546 "Please set a valid breakpoint manually "
555 547 "with the -b option." % bp)
556 548 error(msg)
557 549 return
558 550 # if we find a good linenumber, set the breakpoint
559 551 deb.do_break('%s:%s' % (filename, bp))
560 552 # Start file run
561 553 print "NOTE: Enter 'c' at the",
562 554 print "%s prompt to start your script." % deb.prompt
563 555 ns = {'execfile': py3compat.execfile, 'prog_ns': prog_ns}
564 556 try:
565 557 deb.run('execfile("%s", prog_ns)' % filename, ns)
566 558
567 559 except:
568 560 etype, value, tb = sys.exc_info()
569 561 # Skip three frames in the traceback: the %run one,
570 562 # one inside bdb.py, and the command-line typed by the
571 563 # user (run by exec in pdb itself).
572 564 self.shell.InteractiveTB(etype, value, tb, tb_offset=3)
573 565 else:
574 566 if runner is None:
575 567 runner = self.default_runner
576 568 if runner is None:
577 569 runner = self.shell.safe_execfile
578 570 if 't' in opts:
579 571 # timed execution
580 572 try:
581 573 nruns = int(opts['N'][0])
582 574 if nruns < 1:
583 575 error('Number of runs must be >=1')
584 576 return
585 577 except (KeyError):
586 578 nruns = 1
587 579 twall0 = time.time()
588 580 if nruns == 1:
589 581 t0 = clock2()
590 582 runner(filename, prog_ns, prog_ns,
591 583 exit_ignore=exit_ignore)
592 584 t1 = clock2()
593 585 t_usr = t1[0] - t0[0]
594 586 t_sys = t1[1] - t0[1]
595 587 print "\nIPython CPU timings (estimated):"
596 588 print " User : %10.2f s." % t_usr
597 589 print " System : %10.2f s." % t_sys
598 590 else:
599 591 runs = range(nruns)
600 592 t0 = clock2()
601 593 for nr in runs:
602 594 runner(filename, prog_ns, prog_ns,
603 595 exit_ignore=exit_ignore)
604 596 t1 = clock2()
605 597 t_usr = t1[0] - t0[0]
606 598 t_sys = t1[1] - t0[1]
607 599 print "\nIPython CPU timings (estimated):"
608 600 print "Total runs performed:", nruns
609 601 print " Times : %10.2f %10.2f" % ('Total', 'Per run')
610 602 print " User : %10.2f s, %10.2f s." % (t_usr, t_usr / nruns)
611 603 print " System : %10.2f s, %10.2f s." % (t_sys, t_sys / nruns)
612 604 twall1 = time.time()
613 605 print "Wall time: %10.2f s." % (twall1 - twall0)
614 606
615 607 else:
616 608 # regular execution
617 609 runner(filename, prog_ns, prog_ns, exit_ignore=exit_ignore)
618 610
619 611 if 'i' in opts:
620 612 self.shell.user_ns['__name__'] = __name__save
621 613 else:
622 614 # The shell MUST hold a reference to prog_ns so after %run
623 615 # exits, the python deletion mechanism doesn't zero it out
624 616 # (leaving dangling references).
625 617 self.shell.cache_main_mod(prog_ns, filename)
626 618 # update IPython interactive namespace
627 619
628 620 # Some forms of read errors on the file may mean the
629 621 # __name__ key was never set; using pop we don't have to
630 622 # worry about a possible KeyError.
631 623 prog_ns.pop('__name__', None)
632 624
633 625 self.shell.user_ns.update(prog_ns)
634 626 finally:
635 627 # It's a bit of a mystery why, but __builtins__ can change from
636 628 # being a module to becoming a dict missing some key data after
637 629 # %run. As best I can see, this is NOT something IPython is doing
638 630 # at all, and similar problems have been reported before:
639 631 # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html
640 632 # Since this seems to be done by the interpreter itself, the best
641 633 # we can do is to at least restore __builtins__ for the user on
642 634 # exit.
643 635 self.shell.user_ns['__builtins__'] = builtin_mod
644 636
645 637 # Ensure key global structures are restored
646 638 sys.argv = save_argv
647 639 if restore_main:
648 640 sys.modules['__main__'] = restore_main
649 641 else:
650 642 # Remove from sys.modules the reference to main_mod we'd
651 643 # added. Otherwise it will trap references to objects
652 644 # contained therein.
653 645 del sys.modules[main_mod_name]
654 646
655 647 return stats
656 648
657 649 @skip_doctest
658 650 @line_cell_magic
659 651 def timeit(self, line='', cell=None):
660 652 """Time execution of a Python statement or expression
661 653
662 654 Usage, in line mode:
663 655 %timeit [-n<N> -r<R> [-t|-c]] statement
664 656 or in cell mode:
665 657 %%timeit [-n<N> -r<R> [-t|-c]] setup_code
666 658 code
667 659 code...
668 660
669 661 Time execution of a Python statement or expression using the timeit
670 662 module. This function can be used both as a line and cell magic:
671 663
672 664 - In line mode you can time a single-line statement (though multiple
673 665 ones can be chained with using semicolons).
674 666
675 667 - In cell mode, the statement in the first line is used as setup code
676 668 (executed but not timed) and the body of the cell is timed. The cell
677 669 body has access to any variables created in the setup code.
678 670
679 671 Options:
680 672 -n<N>: execute the given statement <N> times in a loop. If this value
681 673 is not given, a fitting value is chosen.
682 674
683 675 -r<R>: repeat the loop iteration <R> times and take the best result.
684 676 Default: 3
685 677
686 678 -t: use time.time to measure the time, which is the default on Unix.
687 679 This function measures wall time.
688 680
689 681 -c: use time.clock to measure the time, which is the default on
690 682 Windows and measures wall time. On Unix, resource.getrusage is used
691 683 instead and returns the CPU user time.
692 684
693 685 -p<P>: use a precision of <P> digits to display the timing result.
694 686 Default: 3
695 687
696 688
697 689 Examples
698 690 --------
699 691 ::
700 692
701 693 In [1]: %timeit pass
702 694 10000000 loops, best of 3: 53.3 ns per loop
703 695
704 696 In [2]: u = None
705 697
706 698 In [3]: %timeit u is None
707 699 10000000 loops, best of 3: 184 ns per loop
708 700
709 701 In [4]: %timeit -r 4 u == None
710 702 1000000 loops, best of 4: 242 ns per loop
711 703
712 704 In [5]: import time
713 705
714 706 In [6]: %timeit -n1 time.sleep(2)
715 707 1 loops, best of 3: 2 s per loop
716 708
717 709
718 710 The times reported by %timeit will be slightly higher than those
719 711 reported by the timeit.py script when variables are accessed. This is
720 712 due to the fact that %timeit executes the statement in the namespace
721 713 of the shell, compared with timeit.py, which uses a single setup
722 714 statement to import function or create variables. Generally, the bias
723 715 does not matter as long as results from timeit.py are not mixed with
724 716 those from %timeit."""
725 717
726 718 import timeit
727 719 import math
728 720
729 721 # XXX: Unfortunately the unicode 'micro' symbol can cause problems in
730 722 # certain terminals. Until we figure out a robust way of
731 723 # auto-detecting if the terminal can deal with it, use plain 'us' for
732 724 # microseconds. I am really NOT happy about disabling the proper
733 725 # 'micro' prefix, but crashing is worse... If anyone knows what the
734 726 # right solution for this is, I'm all ears...
735 727 #
736 728 # Note: using
737 729 #
738 730 # s = u'\xb5'
739 731 # s.encode(sys.getdefaultencoding())
740 732 #
741 733 # is not sufficient, as I've seen terminals where that fails but
742 734 # print s
743 735 #
744 736 # succeeds
745 737 #
746 738 # See bug: https://bugs.launchpad.net/ipython/+bug/348466
747 739
748 740 #units = [u"s", u"ms",u'\xb5',"ns"]
749 741 units = [u"s", u"ms",u'us',"ns"]
750 742
751 743 scaling = [1, 1e3, 1e6, 1e9]
752 744
753 745 opts, stmt = self.parse_options(line,'n:r:tcp:',
754 746 posix=False, strict=False)
755 747 if stmt == "" and cell is None:
756 748 return
757 749 timefunc = timeit.default_timer
758 750 number = int(getattr(opts, "n", 0))
759 751 repeat = int(getattr(opts, "r", timeit.default_repeat))
760 752 precision = int(getattr(opts, "p", 3))
761 753 if hasattr(opts, "t"):
762 754 timefunc = time.time
763 755 if hasattr(opts, "c"):
764 756 timefunc = clock
765 757
766 758 timer = timeit.Timer(timer=timefunc)
767 759 # this code has tight coupling to the inner workings of timeit.Timer,
768 760 # but is there a better way to achieve that the code stmt has access
769 761 # to the shell namespace?
770 762 transform = self.shell.input_splitter.transform_cell
771 763 if cell is None:
772 764 # called as line magic
773 765 setup = 'pass'
774 766 stmt = timeit.reindent(transform(stmt), 8)
775 767 else:
776 768 setup = timeit.reindent(transform(stmt), 4)
777 769 stmt = timeit.reindent(transform(cell), 8)
778 770
779 771 # From Python 3.3, this template uses new-style string formatting.
780 772 if sys.version_info >= (3, 3):
781 773 src = timeit.template.format(stmt=stmt, setup=setup)
782 774 else:
783 775 src = timeit.template % dict(stmt=stmt, setup=setup)
784 776
785 777 # Track compilation time so it can be reported if too long
786 778 # Minimum time above which compilation time will be reported
787 779 tc_min = 0.1
788 780
789 781 t0 = clock()
790 782 code = compile(src, "<magic-timeit>", "exec")
791 783 tc = clock()-t0
792 784
793 785 ns = {}
794 786 exec code in self.shell.user_ns, ns
795 787 timer.inner = ns["inner"]
796 788
797 789 if number == 0:
798 790 # determine number so that 0.2 <= total time < 2.0
799 791 number = 1
800 792 for i in range(1, 10):
801 793 if timer.timeit(number) >= 0.2:
802 794 break
803 795 number *= 10
804 796
805 797 best = min(timer.repeat(repeat, number)) / number
806 798
807 799 if best > 0.0 and best < 1000.0:
808 800 order = min(-int(math.floor(math.log10(best)) // 3), 3)
809 801 elif best >= 1000.0:
810 802 order = 0
811 803 else:
812 804 order = 3
813 805 print u"%d loops, best of %d: %.*g %s per loop" % (number, repeat,
814 806 precision,
815 807 best * scaling[order],
816 808 units[order])
817 809 if tc > tc_min:
818 810 print "Compiler time: %.2f s" % tc
819 811
820 812 @skip_doctest
821 813 @needs_local_scope
822 814 @line_magic
823 815 def time(self,parameter_s, user_locals):
824 816 """Time execution of a Python statement or expression.
825 817
826 818 The CPU and wall clock times are printed, and the value of the
827 819 expression (if any) is returned. Note that under Win32, system time
828 820 is always reported as 0, since it can not be measured.
829 821
830 822 This function provides very basic timing functionality. In Python
831 823 2.3, the timeit module offers more control and sophistication, so this
832 824 could be rewritten to use it (patches welcome).
833 825
834 826 Examples
835 827 --------
836 828 ::
837 829
838 830 In [1]: time 2**128
839 831 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
840 832 Wall time: 0.00
841 833 Out[1]: 340282366920938463463374607431768211456L
842 834
843 835 In [2]: n = 1000000
844 836
845 837 In [3]: time sum(range(n))
846 838 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
847 839 Wall time: 1.37
848 840 Out[3]: 499999500000L
849 841
850 842 In [4]: time print 'hello world'
851 843 hello world
852 844 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
853 845 Wall time: 0.00
854 846
855 847 Note that the time needed by Python to compile the given expression
856 848 will be reported if it is more than 0.1s. In this example, the
857 849 actual exponentiation is done by Python at compilation time, so while
858 850 the expression can take a noticeable amount of time to compute, that
859 851 time is purely due to the compilation:
860 852
861 853 In [5]: time 3**9999;
862 854 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
863 855 Wall time: 0.00 s
864 856
865 857 In [6]: time 3**999999;
866 858 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
867 859 Wall time: 0.00 s
868 860 Compiler : 0.78 s
869 861 """
870 862
871 863 # fail immediately if the given expression can't be compiled
872 864
873 865 expr = self.shell.prefilter(parameter_s,False)
874 866
875 867 # Minimum time above which compilation time will be reported
876 868 tc_min = 0.1
877 869
878 870 try:
879 871 mode = 'eval'
880 872 t0 = clock()
881 873 code = compile(expr,'<timed eval>',mode)
882 874 tc = clock()-t0
883 875 except SyntaxError:
884 876 mode = 'exec'
885 877 t0 = clock()
886 878 code = compile(expr,'<timed exec>',mode)
887 879 tc = clock()-t0
888 880 # skew measurement as little as possible
889 881 glob = self.shell.user_ns
890 882 wtime = time.time
891 883 # time execution
892 884 wall_st = wtime()
893 885 if mode=='eval':
894 886 st = clock2()
895 887 out = eval(code, glob, user_locals)
896 888 end = clock2()
897 889 else:
898 890 st = clock2()
899 891 exec code in glob, user_locals
900 892 end = clock2()
901 893 out = None
902 894 wall_end = wtime()
903 895 # Compute actual times and report
904 896 wall_time = wall_end-wall_st
905 897 cpu_user = end[0]-st[0]
906 898 cpu_sys = end[1]-st[1]
907 899 cpu_tot = cpu_user+cpu_sys
908 900 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
909 901 (cpu_user,cpu_sys,cpu_tot)
910 902 print "Wall time: %.2f s" % wall_time
911 903 if tc > tc_min:
912 904 print "Compiler : %.2f s" % tc
913 905 return out
914 906
915 907 @skip_doctest
916 908 @line_magic
917 909 def macro(self, parameter_s=''):
918 910 """Define a macro for future re-execution. It accepts ranges of history,
919 911 filenames or string objects.
920 912
921 913 Usage:\\
922 914 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
923 915
924 916 Options:
925 917
926 918 -r: use 'raw' input. By default, the 'processed' history is used,
927 919 so that magics are loaded in their transformed version to valid
928 920 Python. If this option is given, the raw input as typed as the
929 921 command line is used instead.
930 922
931 923 This will define a global variable called `name` which is a string
932 924 made of joining the slices and lines you specify (n1,n2,... numbers
933 925 above) from your input history into a single string. This variable
934 926 acts like an automatic function which re-executes those lines as if
935 927 you had typed them. You just type 'name' at the prompt and the code
936 928 executes.
937 929
938 930 The syntax for indicating input ranges is described in %history.
939 931
940 932 Note: as a 'hidden' feature, you can also use traditional python slice
941 933 notation, where N:M means numbers N through M-1.
942 934
943 935 For example, if your history contains (%hist prints it)::
944 936
945 937 44: x=1
946 938 45: y=3
947 939 46: z=x+y
948 940 47: print x
949 941 48: a=5
950 942 49: print 'x',x,'y',y
951 943
952 944 you can create a macro with lines 44 through 47 (included) and line 49
953 945 called my_macro with::
954 946
955 947 In [55]: %macro my_macro 44-47 49
956 948
957 949 Now, typing `my_macro` (without quotes) will re-execute all this code
958 950 in one pass.
959 951
960 952 You don't need to give the line-numbers in order, and any given line
961 953 number can appear multiple times. You can assemble macros with any
962 954 lines from your input history in any order.
963 955
964 956 The macro is a simple object which holds its value in an attribute,
965 957 but IPython's display system checks for macros and executes them as
966 958 code instead of printing them when you type their name.
967 959
968 960 You can view a macro's contents by explicitly printing it with::
969 961
970 962 print macro_name
971 963
972 964 """
973 965 opts,args = self.parse_options(parameter_s,'r',mode='list')
974 966 if not args: # List existing macros
975 967 return sorted(k for k,v in self.shell.user_ns.iteritems() if\
976 968 isinstance(v, Macro))
977 969 if len(args) == 1:
978 970 raise UsageError(
979 971 "%macro insufficient args; usage '%macro name n1-n2 n3-4...")
980 972 name, codefrom = args[0], " ".join(args[1:])
981 973
982 974 #print 'rng',ranges # dbg
983 975 try:
984 976 lines = self.shell.find_user_code(codefrom, 'r' in opts)
985 977 except (ValueError, TypeError) as e:
986 978 print e.args[0]
987 979 return
988 980 macro = Macro(lines)
989 981 self.shell.define_macro(name, macro)
990 982 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
991 983 print '=== Macro contents: ==='
992 984 print macro,
993 985
994 986 @magic_arguments.magic_arguments()
995 987 @magic_arguments.argument('output', type=str, default='', nargs='?',
996 988 help="""The name of the variable in which to store output.
997 989 This is a utils.io.CapturedIO object with stdout/err attributes
998 990 for the text of the captured output.
999 991
1000 992 CapturedOutput also has a show() method for displaying the output,
1001 993 and __call__ as well, so you can use that to quickly display the
1002 994 output.
1003 995
1004 996 If unspecified, captured output is discarded.
1005 997 """
1006 998 )
1007 999 @magic_arguments.argument('--no-stderr', action="store_true",
1008 1000 help="""Don't capture stderr."""
1009 1001 )
1010 1002 @magic_arguments.argument('--no-stdout', action="store_true",
1011 1003 help="""Don't capture stdout."""
1012 1004 )
1013 1005 @cell_magic
1014 1006 def capture(self, line, cell):
1015 1007 """run the cell, capturing stdout/err"""
1016 1008 args = magic_arguments.parse_argstring(self.capture, line)
1017 1009 out = not args.no_stdout
1018 1010 err = not args.no_stderr
1019 1011 with capture_output(out, err) as io:
1020 1012 self.shell.run_cell(cell)
1021 1013 if args.output:
1022 1014 self.shell.user_ns[args.output] = io
General Comments 0
You need to be logged in to leave comments. Login now