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