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